core 调用webservices_ASP.NET Core教程:在ASP.NET Core中使用HttPClient调用WebService

本文介绍了在ASP.NET Core应用中如何通过HttpClient调用WebService,避免静态引用,提供更佳实践。首先创建一个ASP.NET Core WebAPI项目,然后在ConfigureServices中注入HttpClient。接着在控制器中定义Get方法,调用PostHelper方法发送POST请求到WebService。通过IHttpClientFactory创建客户端,并在appsettings.json中配置URL以实现动态调用。
摘要由CSDN通过智能技术生成

一、前言

在以前的一篇文章中,曾经讲述过如何在ASP.NET Core中调用WebService。但是那种方式是通过静态引用的方式去调用的,如果是在生产环境中,肯定不能使用这种方式去调用,幸运的是微软提供了HttpClient,我们可以通过HttpClient去调用WebService。

二、创建WebService

我们使用VS创建一个WebService,增加一个PostTest方法,方法代码如下

usingSystem.Web.Services;namespaceWebServiceDemo

{///

///WebTest 的摘要说明///

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]

[System.ComponentModel.ToolboxItem(false)]//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。//[System.Web.Script.Services.ScriptService]

public classWebTest : System.Web.Services.WebService

{

[WebMethod]public stringHelloWorld()

{return "Hello World";

}

[WebMethod]public string PostTest(stringpara)

{return $"返回参数{para}";

}

}

}

创建完成以后,我们发布WebService,并部署到IIS上面。保证可以在IIS正常浏览。

三、使用HttpClient调用WebService

我们使用VS创建一个ASP.NET Core WebAPI项目,由于是使用HttpClient,首先在ConfigureServices方法中进行注入

public voidConfigureServices(IServiceCollection services)

{//注入HttpClient

services.AddHttpClient();

services.AddControllers();

}

然后添加一个名为WebServiceTest的控制器,在控制器里面添加一个Get方法,在Get方法里面取调用WebService,控制器代码如下

usingMicrosoft.AspNetCore.Mvc;usingSystem;usingSystem.Collections.Generic;usingSystem.Net;usingSystem.Net.Http;usingSystem.Threading.Tasks;usingSystem.Xml;namespaceHttpClientDemo.Controllers

{

[Route("api/WebServiceTest")]

[ApiController]public classWebServiceTestController : ControllerBase

{readonlyIHttpClientFactory _httpClientFactory;///

///通过构造函数实现注入///

///

publicWebServiceTestController(IHttpClientFactory httpClientFactory)

{

_httpClientFactory=httpClientFactory;

}

[HttpGet]public async TaskGet()

{string strResult = "";try{//url地址格式:WebService地址+方法名称//WebService地址:http://localhost:5010/WebTest.asmx//方法名称: PostTest

string url = "http://localhost:5010/WebTest.asmx/PostTest";//参数

Dictionary dicParam = new Dictionary();

dicParam.Add("para", "1");//将参数转化为HttpContent

HttpContent content = newFormUrlEncodedContent(dicParam);

strResult= awaitPostHelper(url, content);

}catch(Exception ex)

{

strResult=ex.Message;

}returnstrResult;

}///

///封装使用HttpClient调用WebService///

/// URL地址

/// 参数

///

private async Task PostHelper(stringurl, HttpContent content)

{var result = string.Empty;try{using (var client =_httpClientFactory.CreateClient())using (var response = awaitclient.PostAsync(url, content))

{if (response.StatusCode ==HttpStatusCode.OK)

{

result= awaitresponse.Content.ReadAsStringAsync();

XmlDocument doc= newXmlDocument();

doc.LoadXml(result);

result=doc.InnerText;

}

}

}catch(Exception ex)

{

result=ex.Message;

}returnresult;

}

}

}

然后启动调试,查看输出结果

调试的时候可以看到返回结果,在看看页面返回的结果

这样就完成了WebService的调用。生产环境中我们可以URL地址写在配置文件里面,然后程序里面去读取配置文件内容,这样就可以实现动态调用WebService了。我们对上面的方法进行改造,在appsettings.json文件里面配置URL地址

{"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"}

},"AllowedHosts": "*",//url地址

"url": "http://localhost:5010/WebTest.asmx/PostTest"}

修改控制器的Get方法

usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.Extensions.Configuration;usingSystem;usingSystem.Collections.Generic;usingSystem.Net;usingSystem.Net.Http;usingSystem.Threading.Tasks;usingSystem.Xml;namespaceHttpClientDemo.Controllers

{

[Route("api/WebServiceTest")]

[ApiController]public classWebServiceTestController : ControllerBase

{readonlyIHttpClientFactory _httpClientFactory;readonlyIConfiguration _configuration;///

///通过构造函数实现注入///

///

publicWebServiceTestController(IHttpClientFactory httpClientFactory, IConfiguration configuration)

{

_httpClientFactory=httpClientFactory;

_configuration=configuration;

}

[HttpGet]public async TaskGet()

{string strResult = "";try{//url地址格式:WebService地址+方法名称//WebService地址:http://localhost:5010/WebTest.asmx//方法名称: PostTest//读取配置文件里面设置的URL地址//string url = "http://localhost:5010/WebTest.asmx/PostTest";

string url = _configuration["url"];//参数

Dictionary dicParam = new Dictionary();

dicParam.Add("para", "1");//将参数转化为HttpContent

HttpContent content = newFormUrlEncodedContent(dicParam);

strResult= awaitPostHelper(url, content);

}catch(Exception ex)

{

strResult=ex.Message;

}returnstrResult;

}///

///封装使用HttpClient调用WebService///

/// URL地址

/// 参数

///

private async Task PostHelper(stringurl, HttpContent content)

{var result = string.Empty;try{using (var client =_httpClientFactory.CreateClient())using (var response = awaitclient.PostAsync(url, content))

{if (response.StatusCode ==HttpStatusCode.OK)

{

result= awaitresponse.Content.ReadAsStringAsync();

XmlDocument doc= newXmlDocument();

doc.LoadXml(result);

result=doc.InnerText;

}

}

}catch(Exception ex)

{

result=ex.Message;

}returnresult;

}

}

}

这样就可以动态调用WebService了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值