WebSerrvic代码:
[WebMethod]
public string Test(string p1, string p2)
{
return p1 + "_" + p2;
}
以下是 SOAP 1.2 请求和响应示例。所显示的占位符需替换为实际值。
POST /Service1.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/Test"
<?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>
<Test xmlns="http://tempuri.org/">
<p1>string</p1>
<p2>string</p2>
</Test>
</soap:Body>
</soap:Envelope>
方式1:使用FormUrlEncodedContent传参数调用,内部是拼接成一个?+&的格式
public async Task<string> Call()
{
Dictionary<string, string> parameters =new Dictionary<string, string>();
parameters.Add("p1","1");
parameters.Add("p2","2");
string xmlResult = string.Empty;
HttpContent httpContent = new FormUrlEncodedContent(parameters);
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsync("http://localhost/Service1.asmx", httpContent).Result;
var statusCode = response.StatusCode;
if (statusCode == HttpStatusCode.OK)
{
xmlResult = await response.Content.ReadAsStringAsync();
}
return xmlResult;
}
方式二:使用xml的格式调用
public async Task<string> CallByXML()
{
Dictionary<string, string> parameters =new Dictionary<string, string>();
parameters.Add("p1","1");
parameters.Add("p2","2");
string xmlResult = string.Empty;
string xml = $@"
<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>
<Test xmlns="http://tempuri.org/">
<p1>{parameters["p1"]}</p1>
<p2>{parameters["p2"]}</p2>
</Test>
</soap:Body>
</soap:Envelope>
";
HttpContent httpContent = new StringContent(xml, Encoding.UTF8, "text/xml");
httpContent.Headers.Add("SOAPAction", "http://tempuri.org/Test");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsync("http://localhost/Service1.asmx", httpContent).Result;
var statusCode = response.StatusCode;
if (statusCode == HttpStatusCode.OK)
{
xmlResult = await response.Content.ReadAsStringAsync();
}
return xmlResult;
}
方式三:通过服务引用的方式调用
ServiceReference1.Service1Soap service1Soap = new ServiceReference1.Service1SoapClient
(
ServiceReference1.Service1SoapClient.EndpointConfiguration.Service1Soap
);
var res = service1Soap.Test("1", "2").Result;
响应后的XML处理
public string GetResultByXML(string xmlResult)
{
string xmlText=string.Empty;
var xmlobj = new System.Xml.XmlDocument();
xmlobj.LoadXml(xmlResult);
if (!string.IsNullOrEmpty(xmlobj.InnerText))
{
xmlText=xmlobj.InnerText;
}
return xmlText;
}