在没有Web引用的情况下调用c#中的web方法

时间:2015-04-09 10:40:20

标签: c# asp.net

我的错误是什么。 我试图在没有网络推荐的情况下调用asmx web方法,但我在网上有错误:

var result = client.UploadData(WebServiceUrl, data);
  

System.dll中发生了未处理的“System.Net.WebException”类型异常   附加信息:远程服务器返回错误:(500)内部服务器错误。

 class CallWebMethod
{
    public string CallRemoteWebService()
    {
        string ResponseText = "";

        string WebServiceUrl = "http://192.168.1.3/META/services/ws.asmx"; 
        string WebMethodName = "FillXmlData"; 

        using (WebClient client = new WebClient())
        {
            client.Headers.Add("Content-Type", "text/xml; charset=utf-8");
                        var payload = string.Format(@"<?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>
            <{0} xmlns=""http://www.curs.kz/gdmx/services/"" />
          </soap:Body>
         </soap:Envelope>", WebMethodName);

            var data = Encoding.UTF8.GetBytes(payload);
            var result = client.UploadData(WebServiceUrl, data);

            ResponseText = Encoding.Default.GetString(result);

        }
        return ResponseText;
    }
}

1 个答案:

答案 0 :(得分:1)

您需要检查/调试服务器上的错误,而不是客户端上的错误。 IIS通常将其记录在日志文件中。

或者,您可以尝试使用try...catch块输出对控制台的响应,并查看服务器是否返回了一些其他详细信息:

try
{
   string ResponseText = "";

    string WebServiceUrl = "http://192.168.1.3/META/services/ws.asmx"; 
    string WebMethodName = "FillXmlData"; 

    using (WebClient client = new WebClient())
    {
        client.Headers.Add("Content-Type", "text/xml; charset=utf-8");
                    var payload = string.Format(@"<?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>
        <{0} xmlns=""http://www.curs.kz/gdmx/services/"" />
      </soap:Body>
     </soap:Envelope>", WebMethodName);

        var data = Encoding.UTF8.GetBytes(payload);
        var result = client.UploadData(WebServiceUrl, data);

        ResponseText = Encoding.Default.GetString(result);

    }
    return ResponseText;
}
catch (WebException e)
{
   string pageContent = new StreamReader(e.Response.GetResponseStream()).ReadToEnd().ToString();
   Debug.WriteLine(pageContent);
   throw;
}

编辑:您应该在调用Web服务之前在标头(使用值实验)代码中添加soap操作:

client.Headers.Add("SOAPAction", "http://192.168.1.3/META/services/ws.asmx/FillXmlData")