https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0
// Add services to the container. builder.Services.AddHttpClient();
public class BasicModel : PageModel { private readonly IHttpClientFactory _httpClientFactory; public BasicModel(IHttpClientFactory httpClientFactory) => _httpClientFactory = httpClientFactory; public IEnumerable<GitHubBranch>? GitHubBranches { get; set; } public async Task OnGet() { var httpRequestMessage = new HttpRequestMessage( HttpMethod.Get, "https://api.github.com/repos/dotnet/AspNetCore.Docs/branches") { Headers = { { HeaderNames.Accept, "application/vnd.github.v3+json" }, { HeaderNames.UserAgent, "HttpRequestsSample" } } }; var httpClient = _httpClientFactory.CreateClient(); var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage); if (httpResponseMessage.IsSuccessStatusCode) { using var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync(); GitHubBranches = await JsonSerializer.DeserializeAsync <IEnumerable<GitHubBranch>>(contentStream); } } }
标签:http,netcore,httpClientFactory,httpResponseMessage,await,var,public From: https://www.cnblogs.com/Insist-Y/p/17441269.html