在 ASP.NET Core 3.1 中使用 IHttpClientFactory 发出 HTTP 请求-最简单的Get请求

 官方教程:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1

官方教程永远是最权威的,能看懂官方文档就尽量看官方文档!!!!

我整理的步骤:

1、在StartUp的ConfigureServices里通过调用 AddHttpClient 来注册 IHttpClientFactory:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient();
        

2、可以使用依赖项注入 (DI) 来请求 IHttpClientFactory。 以下代码使用 IHttpClientFactory 来创建 HttpClient 实例:(官方demo)

public class BasicUsageModel : PageModel
{
    private readonly IHttpClientFactory _clientFactory;

    public IEnumerable<GitHubBranch> Branches { get; private set; }

    public bool GetBranchesError { get; private set; }

    public BasicUsageModel(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    public async Task OnGet()
    {
        var request = new HttpRequestMessage(HttpMethod.Get,
            "https://api.github.com/repos/aspnet/AspNetCore.Docs/branches");
        request.Headers.Add("Accept", "application/vnd.github.v3+json");
        request.Headers.Add("User-Agent", "HttpClientFactory-Sample");

        var client = _clientFactory.CreateClient();

        var response = await client.SendAsync(request);

        if (response.IsSuccessStatusCode)
        {
            using var responseStream = await response.Content.ReadAsStreamAsync();
            Branches = await JsonSerializer.DeserializeAsync
                <IEnumerable<GitHubBranch>>(responseStream);
        }
        else
        {
            GetBranchesError = true;
            Branches = Array.Empty<GitHubBranch>();
        }
    }
}

在实际使用中,我们经常会用NewtonJson序列化,给一个简单的Demo:

  string api_domain = _config.GetSection("OuterApi:open-api").Value;
                string api_url = $"{api_domain}/common-service/api/basic?code={code}";
                var request = new HttpRequestMessage(HttpMethod.Get, api_url);
                request.Headers.Add("Accept", "application/vnd.github.v3+json");


                var client = _clientFactory.CreateClient();

                var response = await client.SendAsync(request);

                Result<List<OpenApiDictModel>> apiRet = new Result<List<OpenApiDictModel>>();
                if (response.IsSuccessStatusCode)
                {
                    string responseStr = await response.Content.ReadAsStringAsync();
                    apiRet = JsonConvert.DeserializeObject<Result<List<OpenApiDictModel>>>(responseStr);
                }