在ASP.NET Core 6.0 Web API中,可能会发现使用[AllowAnonymous]特性无法绕过授权。这是由于在6.0版本中,中间件处理AllowAnonymous特性的位置进行了调整。解决方法是手动添加中间件以覆盖这一行为。
在程序的Startup.cs文件中,找到Configure方法,并在app.UseRouting()之后添加以下代码:
app.UseAuthorization(); app.UseAuthentication();
这将确保AllowAnonymous特性在授权和身份验证之前得到处理,从而使其生效。
完整代码示例:
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(); services.AddAuthorization(); services.AddControllers(); }
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
现在,您可以在控制器或操作的顶部使用[AllowAnonymous]特性来绕过授权,访问受限制的资源。
上一篇:ASP.NETCore6.0WebAPI在迁移到最小托管模型后的集成测试
下一篇:ASP.NETCore6.0WebApplicationnotredirectingtoidentityserveronauthorization