IHttpClientFactory 踩过的坑
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) { var responseStream = await response.Content.ReadAsStreamAsync(); Branches = await JsonSerializer.DeserializeAsync <IEnumerable<GitHubBranch>>(responseStream); } else { GetBranchesError = true; Branches = Array.Empty<GitHubBranch>(); } }
仔细看没什么问题吧?
using var responseStream = await response.Content.ReadAsStreamAsync();
使用的时候没加using,导致并发连接数高一直没有释放,致使应用奔溃