如何在.NET Core 2.0中通过Web API调用GetReportService Web服务
嘿,针对你在.NET Core 2.0里的两个Web服务调用问题,我给你详细拆解下解决方案:
一、用Connected Services消费Web服务
.NET Core 2.0里可以通过Microsoft WCF Web Service Reference Provider这个工具来添加Web服务引用(属于Connected Services的功能),步骤很直观:
- 打开你的.NET Core 2.0项目,右键点击解决方案资源管理器里的「Connected Services」,选择「Add Connected Service」
- 在弹出的服务列表里找到「Microsoft WCF Web Service Reference Provider」,点击「Configure」
- 输入你的ASMX服务的WSDL地址(通常是原端点加
?wsdl后缀,比如http://xxx1/usa/report.asmx?wsdl),然后点击「Go」加载元数据 - 工具会列出服务里的所有操作方法,你可以自定义生成代码的命名空间,确认后点击「Finish」
- 生成完成后,项目里会自动出现服务代理类,你就可以像调用本地方法一样调用远程Web服务了
二、调用GetReportService的具体实现
针对你的GetReportService(端点http://xxx1/usa/report.asmx,POST传id123),有两种常见的调用方式:
方式1:用Connected Services生成的代理类调用
假设生成的代理命名空间是YourProject.ReportService,服务客户端类是ReportSoapClient,对应的调用方法是GetReportAsync(具体名称取决于WSDL里的定义):
using YourProject.ReportService; public async Task<YourReportModel> InvokeGetReport() { // 实例化服务客户端 var client = new ReportSoapClient(ReportSoapClient.EndpointConfiguration.ReportSoap); try { // 调用服务,传入参数id123 var reportResult = await client.GetReportAsync("id123"); return reportResult; } finally { // 确保客户端连接关闭 await client.CloseAsync(); } }
小提示:如果服务的参数名不是
id,一定要换成WSDL里定义的实际参数名,比如如果方法是GetReport(string reportId),就传对应的参数值。
方式2:手动用HttpClient调用(无需生成代理)
如果你不想依赖自动生成的代理,也可以直接用HttpClient构造SOAP请求来调用ASMX服务:
using System.Net.Http; using System.Text; public async Task<string> CallGetReportManually() { // 构造符合SOAP规范的请求体 var soapRequestBody = @"<?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> <GetReport xmlns=""http://your-service-namespace/""> <id>id123</id> </GetReport> </soap:Body> </soap:Envelope>"; using (var httpClient = new HttpClient()) { // 添加SOAPAction请求头,值要和服务定义的命名空间+方法名对应 httpClient.DefaultRequestHeaders.Add("SOAPAction", "\"http://your-service-namespace/GetReport\""); // 构造请求内容,指定content-type为text/xml var requestContent = new StringContent(soapRequestBody, Encoding.UTF8, "text/xml"); // 发送POST请求到服务端点 var response = await httpClient.PostAsync("http://xxx1/usa/report.asmx", requestContent); // 确保请求成功 response.EnsureSuccessStatusCode(); // 读取返回的SOAP响应 return await response.Content.ReadAsStringAsync(); } }
注意:要把
http://your-service-namespace/替换成你ASMX服务实际的命名空间(可以从WSDL的<definitions>标签的targetNamespace属性里找到),SOAPAction的URL也要严格对应。
内容的提问来源于stack exchange,提问作者user1647160
相关产品推荐
相关产品推荐

