已经明确指出有two ways https://learn.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/additional-scenarios?view=aspnetcore-3.1#attach-tokens-to-outgoing-requests要为传出请求配置消息处理程序,建议实现自定义消息处理程序。
再次......您实现一个自定义消息处理程序以配置消息处理程序。这就是定制的唯一目的。当然,您可以重写 SendAsync 方法,如果这样的操作到位,您就知道自己在做什么,并且可以适当地执行该操作。但并不是引入错误并实际上使 SendAsync 无效的一种方式。
这是自定义消息处理程序的实现:
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
--
public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
{
public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,
NavigationManager navigationManager)
: base(provider, navigationManager)
{
ConfigureHandler(
authorizedUrls: new[] { "https://localhost:44370" });
}
}
上面解决了您遇到的问题...也就是说,配置范围属性(scopes: new[] { "admin" });
),可以省略。
以下是改进代码的一些建议:
创建一个名为 HttpClient 的服务,如下所示。
builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>
().CreateClient("ServerAPI"));
并将其注入到您的组件中,如下所示:@inject HttpClient Http
并像这样使用它:
protected override async Task OnInitializedAsync()
{
try
{
message= await Http.GetFromJsonAsync<string>("api/message");
}
catch (AccessTokenNotAvailableException exception)
{
exception.Redirect();
}
}
注意:为了使用 GetFromJsonAsync 方法,您应该安装
System.Net.Http.Json包
注意,上面是处理Http请求的正确方法。这包括将用户重定向到登录页面。当然,您可以生成想要向用户显示的任何消息,但重定向是正确的方法。
应用上述建议的更改后,您的 Program.Main 方法应具有以下设置(注意顺序):
builder.Services.AddScoped<CustomAuthorizationMessageHandler>();
builder.Services.AddHttpClient("ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<CustomAuthorizationMessageHandler>();
builder.Services.AddTransient(sp =>
sp.GetRequiredService<IHttpClientFactory>().CreateClient("ServerAPI"));