VS2010,C#,. NET 4
我创建了2个应用程序:Web服务和Windows窗体应用程序(两者都在同一台PC上运行)。这是代码:
WEBSERVICE:
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "message";
}
}
WINDOWS APPLICATION:
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());
这项工作非常精细。我从包含消息的webservice获得响应。 现在我将应用程序2的应用程序更改为:
WEB服务:
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld(string message)
{
return message;
}
}
WINDOWS FORMS APPLICATION:
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引用。
答案 0 :(得分:0)
我注意到在调用GetResponse()之前不要关闭请求流。我没有测试过,但docs中的示例关闭了请求流。无论哪种方式,这都是很好的做法,所以先尝试一下。
即
postdataStream.Write(byte1, 0, byte1.Length);
postDataStream.Close();
WebResponse res = req.GetResponse();