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

时间:2020-09-22 12:42:00

标签: blazor asp.net-core-identity blazor-webassembly

为了安全起见,我创建了一个带有“个人帐户”的ASP.NET托管项目。 “ .Client”应用程序在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客户端添加到请求“ HttpClient”的任何其他服务。

如果我将服务添加到Program类:

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

1 个答案:

答案 0 :(得分:1)

您可以根据每个服务注册具有不同配置的多个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}");
    }
}

Microsoft Docs的更多信息