在Blazor WebAssembly中,如果想要阻止WebApi方法的AllowAnonymous特性生效,可以通过自定义一个AuthorizationMessageHandler来实现。
首先,创建一个名为CustomAuthorizationMessageHandler的类,继承自AuthorizationMessageHandler。
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.Extensions.Logging;
public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
{
public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,
ILoggerFactory loggerFactory,
NavigationManager navigationManager,
IAuthorizationService authorizationService)
: base(provider, loggerFactory, navigationManager, authorizationService)
{
ConfigureHandler();
}
private void ConfigureHandler()
{
// 在这里可以自定义处理逻辑来阻止AllowAnonymous特性生效
// 例如,可以检查当前请求的URL是否为WebApi的URL,然后判断是否需要进行授权
// 这里是一个示例,假设WebApi的URL路径为/api
// 如果请求的URL路径包含/api,则不允许AllowAnonymous特性生效
var apiPath = "/api";
if (NavigationManager.Uri.Contains(apiPath))
{
ConfigureHandler(new[] { apiPath });
}
}
}
接下来,在Program.cs文件中,注册CustomAuthorizationMessageHandler。
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace BlazorApp
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add("#app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
// 注册自定义的AuthorizationMessageHandler
builder.Services.AddHttpClient("ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler();
await builder.Build().RunAsync();
}
}
}
现在,CustomAuthorizationMessageHandler将会在每个请求之前进行检查,并阻止AllowAnonymous特性生效。你可以根据自己的需求,在ConfigureHandler方法中添加自定义的逻辑进行授权判断。