【问题标题】:Best practice to create HttpClient in .NET Core 2 [closed]在 .NET Core 2 中创建 HttpClient 的最佳实践 [关闭]
【发布时间】:2018-12-22 11:09:26
【问题描述】:

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

HttpClients 将被创建和缓存,然后从缓存中检索

    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");
    }
}

【问题讨论】:

标签: c# asp.net-core httpclient


【解决方案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>();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2020-02-05
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2021-01-16
    • 1970-01-01
    • 2011-10-29
    相关资源
    最近更新 更多