如何使用C#发送/接收SOAP请求和响应?

private static string WebServiceCall(string methodName) { WebRequest webRequest = WebRequest.Create("http://localhost/AccountSvc/DataInquiry.asmx"); HttpWebRequest httpRequest = (HttpWebRequest)webRequest; httpRequest.Method = "POST"; httpRequest.ContentType = "text/xml; charset=utf-8"; httpRequest.Headers.Add("SOAPAction: http://tempuri.org/" + methodName); httpRequest.ProtocolVersion = HttpVersion.Version11; httpRequest.Credentials = CredentialCache.DefaultCredentials; Stream requestStream = httpRequest.GetRequestStream(); //Create Stream and Complete Request StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.ASCII); StringBuilder soapRequest = new StringBuilder(""); soapRequest.Append("Sam"); soapRequest.Append(""); streamWriter.Write(soapRequest.ToString()); streamWriter.Close(); //Get the Response HttpWebResponse wr = (HttpWebResponse)httpRequest.GetResponse(); StreamReader srd = new StreamReader(wr.GetResponseStream()); string resulXmlFromWebService = srd.ReadToEnd(); return resulXmlFromWebService; } 

我尝试了不同的代码来发送/接收soap响应,但都失败了"The remote server returned an error: (500) Internal Server Error."

我可以使用SoapUI访问相同的服务。 我也可以调用这个方法。 我在这个论坛中读到,我得到500错误的原因可能是错误的标题。 我validation了标题,似乎没问题。 如果有人可以帮忙,我将不胜感激。

以下是SOAP请求示例:

 POST /AccountSvc/DataInquiry.asmx HTTP/1.1 Host: abc.def.gh.com Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://tempuri.org/GetMyName"     string    

我使用上面的示例请求来执行该方法,并且它工作正常。 这是我通过的Soap请求:

 Sam 

编辑:

我已经在WebServiceCall中更新了上面的代码,该代码适用于.asmx服务。 但是相同的代码不适用于WCF服务。 为什么?

url不同。

  • http://localhost/AccountSvc/DataInquiry.asmx

  • /acctinqsvc/portfolioinquiry.asmx

首先解决此问题,就好像Web服务器无法解析您尝试POST的URL,您甚至不会开始处理请求所描述的操作。

您应该只需要为ASMX根URL创建WebRequest,即: http://localhost/AccountSvc/DataInquiry.asmx ,并在SOAPAction标头中指定所需的方法/操作。

SOAPAction标头值不同。

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

  • http://tempuri.org/GetMyName

您应该能够通过转到正确的ASMX URL并附加?wsdl来确定正确的SOAPAction

标记下面应该有一个标记,它与您尝试执行的操作相匹配,该标记似乎是GetMyName

请求正文中没有包含SOAP XML的XML声明。

您在HttpRequest的ContentType中指定text/xml而不是charset。 也许这些默认为us-ascii ,但是你不知道你是不是在指定它们!

SoapUI创建的XML包含一个XML声明,它指定utf-8的编码,它也匹配提供给HTTP请求的Content-Type,它是: text/xml; charset=utf-8 text/xml; charset=utf-8

希望有所帮助!