【发布时间】:2012-03-12 20:52:58
【问题描述】:
VS2010、C#、.NET 4
我创建了 2 个应用程序:一个 Web 服务和一个 Windows 窗体应用程序(都在同一台 PC 上运行)。这是代码:
网络服务:
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "message";
}
}
Windows 应用程序:
HttpWebRequest req =(HttpWebRequest)WebRequest.Create("http://localhost:20848/Service1.asmx/HelloWorld");
req.Credentials = CredentialCache.DefaultCredentials;
req.Method = "POST";
//Set the content type of the data being posted.
req.ContentType = "application/text";
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string txtOutput = sr.ReadToEnd();
Console.WriteLine(sr.ReadToEnd());
这很好用。我从包含消息的网络服务中得到响应。 现在我将应用程序 2 应用程序更改为:
网络服务:
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld(string message)
{
return message;
}
}
WINDOWS 窗体应用:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:20848/Service1.asmx/HelloWorld");
req.Credentials = CredentialCache.DefaultCredentials;
req.Method = "POST";
string inputData = "sample webservice";
string postData = "message=" + inputData;
byte[] byte1 = System.Text.ASCIIEncoding.ASCII.GetBytes(postData);
req.ContentLength = byte1.Length;
Stream postdataStream = req.GetRequestStream();
//Set the content type of the data being posted.
req.ContentType = "application/text";
postdataStream.Write(byte1, 0, byte1.Length);
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string txtOutput = sr.ReadToEnd();
Console.WriteLine(sr.ReadToEnd());
这在 req.GetResponse() 处失败; “它表示底层连接已关闭”。谁能告诉我这里的代码有什么问题。注意 - 我必须只使用 WebRequests 访问 WebMethods。我不想添加 Web 引用。
【问题讨论】:
-
你到底在做什么?为什么不使用“添加服务参考”?您不应该使用 ASMX 服务和“添加 Web 参考”进行新开发。
-
您的服务是否设置为执行 SOAP 或“HttpPost”?
-
如果您解释为什么不能添加 Web 服务引用,也许有人能更好地帮助您。从实际的角度来看,这没有什么意义。
标签: .net winforms webrequest webmethod