我用;个人账户";为了安全起见。";。客户端";该应用程序在Program.cs类中附带了以下内容。
builder.Services.AddHttpClient("BlazorApp1.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
// Supply HttpClient instances that include access tokens when making requests to the server project
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>)
.CreateClient("BlazorApp1.ServerAPI"));
我理解第一行创建了一个HttpClient服务,它为每个请求添加一个令牌。第二行将该HTTP客户端添加到请求"HTTP"的任何其他服务;HttpClient";。
如果我将服务添加到程序类:
builder.Services.AddScoped<IPostService, PostService>();
它看起来像这样:
public class SomeService: ISomeService
{
private readonly HttpClient _httpClient;
public UserActivityService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<SomeOutputClass> Get()
{
return await _httpClient.GetFromJsonAsync<SomeOutputClass>($"{apiUrl}");
}
}
则该服务将使用";BlazorApp1.ServerAPI";HttpClient始终存在,这需要身份验证。
我想做的是能够有一个不使用这个";BlazorApp1.ServerAPI";HttpClient,但使用不需要授权的HttpClient。有办法做到这一点吗?也许可以创建一个单独的名为HttpClient的服务,并将其传递给服务,如:
builder.Services.AddScoped<IPostService, PostService>(OtherHttpClient);
您可以根据每个服务注册具有不同配置的多个http客户端,如下所示:
程序.cs
builder.Services.AddHttpClient<IPostService, PostService>(client =>
{
client.BaseAddress = new Uri("https://apiUrl");
});
那么你的服务会是这样的:
public class PostService : IPostService
{
private readonly HttpClient httpClient;
public PostService (HttpClient httpClient)
{
this.httpClient = httpClient;
}
public Task<SomeType> Get()
{
return await _httpClient.GetFromJsonAsync<SomeOutputClass>($"{apiUrl}");
}
}
来自Microsoft Docs 的更多信息