在.NET Core 2中创建HttpClient的最佳实践

时间:2018-12-22 11:09:27

标签: c# asp.net-core httpclient

让HttpClientWrapper在.net core 2中创建HttpClient是一种好习惯吗?

将创建并缓存HttpClient,然后从缓存中获取

    public class HttpClientWrapper : IHttpClientWrapper
    {
    private IMemoryCache cache;
    public HttpClientWrapper(IMemoryCache _cache)
    {
        cache = _cache;
    }

    public HttpClient CreateClient(string baseUrl)
    {
        HttpClient httpClient;
        if (!cache.TryGetValue(baseUrl, out httpClient))
        {

             MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
             //cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
             cacheExpirationOptions.SlidingExpiration = new TimeSpan(0, 30, 0);
             cacheExpirationOptions.Priority = CacheItemPriority.Normal;


            httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri(baseUrl);
            cache.Set<HttpClient>(baseUrl, httpClient, cacheExpirationOptions);
        }
        return httpClient;
    }
}

及其用法

[Route("api/[controller]")]
[ApiController]
public class CustomValuesController : ControllerBase
{
    private readonly HttpClient httpClient;
    private readonly HttpClient httpClient1;

    public CustomValuesController(Common.IHttpClientWrapper _httpClientWrapper)
    {
        httpClient = _httpClientWrapper.CreateClient("http://localhost:9000");
        httpClient1 = _httpClientWrapper.CreateClient("http://localhost:9001");
    }
}

1 个答案:

答案 0 :(得分:1)

我认为使用named-clients

是个好方法
services.AddHttpClient("github", c =>
{
c.BaseAddress = new Uri("https://api.github.com/");
// Github API versioning
c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
// Github requires a user-agent
c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
});

及其用法

public class NamedClientModel : PageModel
{
private readonly IHttpClientFactory _clientFactory;

public IEnumerable<GitHubPullRequest> PullRequests { get; private set; }

public bool GetPullRequestsError { get; private set; }

public bool HasPullRequests => PullRequests.Any();

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

public async Task OnGet()
{
    var request = new HttpRequestMessage(HttpMethod.Get, 
        "repos/aspnet/docs/pulls");

    var client = _clientFactory.CreateClient("github");

    var response = await client.SendAsync(request);

    if (response.IsSuccessStatusCode)
    {
        PullRequests = await response.Content
            .ReadAsAsync<IEnumerable<GitHubPullRequest>>();
    }
    else
        {
        GetPullRequestsError = true;
        PullRequests = Array.Empty<GitHubPullRequest>();
        }
    }
}