创建一个名为HttpClientTest的Web API项目
新建Clients文件夹,用于存放自定义的HttpClient
在Clients下新建一个MyHttpClient类
代码为:
namespace HttpClientTest.Clients { public class MyHttpClient { private readonly HttpClient _client; public MyHttpClient(HttpClient client) { _client = client; } public async Task<string> ShowAsync() { return await _client.GetStringAsync("https://www.baidu.com"); } } }
将自定义的MyHttpClient服务注册进容器中
services.AddHttpClient<MyHttpClient>();
新建一个TestController来对我们的MyHttpClient做一个测试
using HttpClientTest.Clients; using Microsoft.AspNetCore.Mvc; namespace HttpClientTest.Controllers { [ApiController] [Route("[controller]/[action]")] public class TestController : ControllerBase { private readonly MyHttpClient _myHttpClient; public TestController(MyHttpClient myHttpClient) { _myHttpClient = myHttpClient; } [HttpGet] public async Task<object> GetAsync() { return await _myHttpClient.ShowAsync(); } } }
访问GetAsync接口,发现成功返回了百度首页的html内容
很多时候,我们希望通过相对路径的方式来对远程服务进行访问
可以把MyHttpClient改为:
namespace HttpClientTest.Clients { public class MyHttpClient { private readonly HttpClient _client; public MyHttpClient(HttpClient client) { _client = client; } public async Task<string> ShowAsync() { //return await _client.GetStringAsync("https://www.baidu.com"); return await _client.GetStringAsync("/"); } } }
在注册服务时就要配置基地址
services.AddHttpClient<MyHttpClient>(client => { client.BaseAddress = new Uri("https://www.baidu.com"); });
到此这篇关于.net HttpClient简单使用的文章就介绍到这了,更多相关.net HttpClient使用内容请搜索阿兔在线工具以前的文章或继续浏览下面的相关文章希望大家以后多多支持阿兔在线工具!