在 Blazor WASM 中,如何创建不使用身份验证的服务?

In Blazor WASM, how can I create a service that doesn't use authentication?

为了安全起见,我创建了一个带有“个人帐户”的 ASP.NET 托管项目。 “.Client”应用程序在 Program.cs class.

中附带以下内容
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 客户端添加到请求“HttpClient”的任何其他服务。

如果我向程序添加服务 class:

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客户端:

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

来自微软的更多信息Docs