gpt4 book ai didi

c# - Web 服务和表单翻译器

转载 作者:太空宇宙 更新时间:2023-11-03 16:03:34 27 4
gpt4 key购买 nike

我的项目是编写一个网络服务和一个使用它的网络表单。它应该有两个文本框和一个按钮。用户在第一个文本框中输入文本的首字母缩写词并按下按钮。 Web 服务将 textbox1 条目与字典文件进行比较,并在第二个文本框中显示生成的完整单词。这是我到目前为止的代码,我真的很难让它工作,任何帮助将不胜感激。此时我有“类型或命名空间定义,或预期文件结尾”错误。这是我的两个文件。

Default.aspx.cs:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
private Dictionary<string, string> _dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
protected void Page_Load(object sender, EventArgs e)
{
using (var reader = new StreamReader(File.OpenRead(@"C:/dictionary.csv")))
{
while (!reader.EndOfStream)
{
string[] tokens = reader.ReadLine().Split(';');
_dictionary[tokens[0]] = tokens[1];
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
localhost.Service obj = new localhost.Service();
TextBox1.Text = (obj.Translate());
}
}

服务.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]

public class Service : System.Web.Services.WebService
{
public Service () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string Translate(string input)
{
string output;
if(_dictionary.TryGetValue(input, out output))
return output;

// Obviously you might not want to throw an exception in this basis example,
// you might just go return "ERROR". Up to you, but those requirements are
// beyond the scope of the question! :)
throw new Exception("Sinatra doesn't know this ditty");
}
}

}

最佳答案

不确定问题是否仍未得到解答。但这是我的建议。

在 Web 服务文件中,例如 Service1.cs,您没有声明 _dictionary 对象。因此,您将在服务的构造函数中移动字典对象声明和初始化。

像下面这样的东西。

 public WebService1()
{
using (var reader = new StreamReader(File.OpenRead(@"C:/dictionary.csv")))
{
while (!reader.EndOfStream)
{
string[] tokens = reader.ReadLine().Split(',');
_dictionary[tokens[0]] = tokens[1];
}
}
}

同样在 split 方法中,我假设您想使用逗号而不是分号(在您的示例中使用)。

然后在服务的消费中,你会做一些像下面这样的事情。我不确定您尝试使用样本中的本地主机对象做什么。

 ServiceReference1.WebService1SoapClient obj = new WebService1SoapClient();
TextBox2.Text = obj.Translate(TextBox1.Text);

希望这对您有所帮助。

-达沃德。

关于c# - Web 服务和表单翻译器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20337286/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com