C#使用RestSharp调用.asmx接口示例

如题,厂家提供的接口是.asmx接口,使用text/xml传输方式。

我们决定使用RestSharp进行对接

一,接口地址

使用接口地址创建RestClient对象时,一定要注意接口地址到.asmx即可,不能带上具体接口名称/xxxx

http://127.0.0.1:8081/AOIService.asmx

二,添加Header

var request = new RestRequest();
//头部信息
request.AddHeader("Content-Type", "text/xml; charset=utf-8");//x-www-form-urlencoded//json
request.AddHeader("Content-Length", "length");
request.AddHeader("SOAPAction", $"http://tempuri.org/{apiName}");
request.Method = Method.Post;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 ;

三,参数body

<?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>
    <AOICheckIn xmlns="http://tempuri.org/">
      <equipmentName>string</equipmentName>
      <waferId>string</waferId>
      <Wsid>string</Wsid>
      <userId>string</userId>
    </AOICheckIn>
  </soap:Body>
</soap:Envelope>
// 构建SOAP请求体(替换命名空间和方法名)
string soapBody = $"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<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/\">\r\n  <soap:Body>\r\n    <{apiName} xmlns=\"http://tempuri.org/\">\r\n      {string.Join("\r\n", paramList)}\r\n    </{apiName}>\r\n  </soap:Body>\r\n</soap:Envelope>";
           
request.AddParameter("text/xml", soapBody, ParameterType.RequestBody);

 

四,请求结果

var response = Client.Execute(request);
if (!response.IsSuccessful)
{
    return Result.Fail(2, $"请求失败:{response.ErrorMessage}");
}
else
{

}

 

posted on 2025-09-05 15:54  lopengye  阅读(33)  评论(0)    收藏  举报

导航