【问题标题】:WebRequest and WebMethods interopWebRequest 和 WebMethods 互操作
【发布时间】: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


【解决方案1】:

我注意到您在调用 GetResponse() 之前没有关闭请求流。我还没有测试过,但是docs 中的示例关闭了请求流。无论哪种方式,这都是一种很好的做法,所以请先尝试一下。

即

postdataStream.Write(byte1, 0, byte1.Length);
postDataStream.Close();
WebResponse res = req.GetResponse();

【讨论】:

  • 好的。破解数据包嗅探器(Fiddler、Wireshark 等)。请求真的被发送了吗?如,是服务器关闭连接吗?或者框架甚至没有发送它?其他要尝试的东西...应用程序/文本...它只是纯文本。不应该是文本/纯文本吗?我注意到您使用的是 ASCII 编码。我手头没有 http 规范,但我会给 UTF8 一个破解。
猜你喜欢
  • 2010-12-17
  • 2012-08-09
  • 2011-09-22
  • 2011-11-18
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
相关资源
最近更新 更多