4

我正在尝试在使用 WebClient 访问 Web 服务上的 WebMethod 的类中创建一个方法,并且遇到了问题。在 Windows 上使用 VS2010。

首先,是的,我知道我可以在类库中创建对 Web 服务的 Web 引用,当然这是设计时绑定。但是,我需要能够使用仅在运行时可用的信息来访问 Web 服务。这有一个商业原因,我不会在这里讨论,请随它去吧。

这似乎可以使用 System.Net 命名空间中的 WebClient 类。事实上,我能够访问有问题的服务,但我发送给它的数据似乎格式不正确,尽管我可以说它是一个格式正确的 SOAP 消息。

WebException 包含以下消息:“远程服务器返回错误:(415) 不支持的媒体类型。”

这是代码:

public string DoingBusiness()
{
    WebClient client = new WebClient();
    string destUri = "http://localhost/Service/Service.asmx?op=CommunicationsCheck";

    StreamReader reader = new StreamReader(@"CommCheck.xml");
    string data = String.Format(reader.ReadToEnd(), "The End is Near!");
    reader.Close();

    string response = client.UploadString(destUri, data);

    return response;
}

撇开敏感的实际 xmlns,上面的 StreamReader 读取的数据如下所示:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <CommunicationsCheck xmlns="http://.../">
      <communication>{0}</communication>
    </CommunicationsCheck>
  </soap:Body>
</soap:Envelope> 

这看起来像一个完美的 SOAP 消息。当然,“{0}”会用有效负载字符串填充。如果 WebMethod "CommunicationsCheck(string communication) 成功运行,它将返回:

<?xml version="1.0" encoding="utf-8" ?> 
<string xmlns="http://[service url]/">You sent 'The End is Near!'</string> 

如果我通过浏览器或通过设计时 Web 参考访问服务,它会执行此操作。

所以,问题是,我在这里做错了什么,我得到了“(415)不支持的媒体类型”

WebClient 上是否有需要设置的属性?我是否可能需要提供包含 UserAgent 的 Header?或者是其他东西?

4

1 回答 1

8

该死。我想我应该让别人回答这个问题,但回答自己的问题是可以接受的,如果你自己找到的话。

无论如何,对这个问题的一些进一步研究似乎表明我的一个猜测,即我可能需要设置一些 Header 属性,是一种可能的解决方案。研究表明,该属性将是“内容类型”,需要设置为“文本/xml”。所以我添加了这一行:

client.Headers.Add("content-type", "text/xml");

就在 UploadString 方法调用之前。

答对了!

出现了预期的响应。

有没有人注意到,一旦提出问题,对令人困惑的问题的答案有时会变得不言而喻,但不是在此之前?有趣的现象。

于 2012-05-04T17:55:30.113 回答