aspnetcore 如何取消AddAuthentication后未认证通过的重定向
时间: 2024-10-08 10:20:08 浏览: 35
在ASP.NET Core中,当你使用`AddAuthentication`添加了身份验证并在未认证的情况下启用自动重定向时,如果没有提供有效的凭证,应用程序会默认跳转到指定的登录页面让用户输入认证信息。如果你想取消这种自动重定向并直接返回404错误,你可以采取以下步骤:
1. **关闭自动授权中间件**:在Startup.cs文件的ConfigureServices和Configure方法中,可以明确地排除IdentityOptions或ApplicationBuilder,不让它添加身份验证中间件。例如,移除`UseAuthentication()`。
```csharp
services.AddControllers().RequireAuthorization(false); // 或者
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { requireAuth = false }
);
});
```
2. **自定义错误处理**:创建一个自定义的ErrorController或在全局异常处理器中处理401未经授权的情况,返回404状态码。
```csharp
app.Use(async (context, next) =>
{
try
{
await next();
}
catch (UnauthorizedAccessException ex)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Not Found");
}
});
```
阅读全文