我正在尝试在使用 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?或者是其他东西?