如何在C#中调用返回XML响应的WebService函数(如AddInteger)
C#调用XML格式WebService函数的方法
下面针对你提到的AddInteger两数相加函数,提供两种最常用的调用方式:
方法一:添加服务引用(Visual Studio 快速实现)
这是最省心的方式,工具会自动帮你处理XML序列化和请求逻辑:
- 打开Visual Studio,在项目上右键 → 「添加」→ 「服务引用」
- 在地址栏输入WebService的WSDL地址,点击「转到」,工具会自动识别出包括
AddInteger在内的所有可用方法 - 自定义一个命名空间(比如
MathWebService),点击「确定」完成引用添加 - 调用代码示例:
// 实例化服务客户端 var client = new MathWebService.MathServiceClient(); // 直接调用AddInteger方法,传入参数 long sumResult = client.AddInteger(15, 25); // 输出结果 Console.WriteLine($"两数相加结果:{sumResult}"); // 关闭客户端释放资源 client.Close();
方法二:手动构造XML请求(HTTP POST方式)
如果不想依赖自动生成的服务引用,也可以直接构造XML请求发送:
using System; using System.Net.Http; using System.Xml.Linq; class Program { static async System.Threading.Tasks.Task Main(string[] args) { var httpClient = new HttpClient(); // 替换成实际的WebService端点地址 string serviceUrl = "http://your-webservice-address/Service.asmx"; // 构造符合要求的SOAP请求XML string xmlRequest = @" <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""> <soap:Body> <AddInteger xmlns=""http://your-webservice-namespace/""> <Arg1>15</Arg1> <Arg2>25</Arg2> </AddInteger> </soap:Body> </soap:Envelope>"; // 设置请求头和内容类型 var content = new StringContent(xmlRequest, System.Text.Encoding.UTF8, "text/xml"); content.Headers.Add("SOAPAction", "\"http://your-webservice-namespace/AddInteger\""); // 发送请求并获取响应 var response = await httpClient.PostAsync(serviceUrl, content); string xmlResponse = await response.Content.ReadAsStringAsync(); // 解析响应XML,提取结果 XDocument doc = XDocument.Parse(xmlResponse); XNamespace ns = "http://your-webservice-namespace/"; string result = doc.Descendants(ns + "AddIntegerResult").First().Value; Console.WriteLine($"两数相加结果:{long.Parse(result)}"); } }
注意事项
- 代码中的
http://your-webservice-address/Service.asmx和http://your-webservice-namespace/需要替换成实际的WebService地址和命名空间(可从WSDL文档中获取) - .NET Core/.NET 5+环境下,建议复用
HttpClient实例,避免频繁创建造成资源浪费 - 服务引用方式适合大多数场景,无需手动处理XML结构;手动请求方式更灵活,适合需要自定义请求细节的场景
内容的提问来源于stack exchange,提问作者SKYLER
相关产品推荐
相关产品推荐

