You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Web API身份认证异常:未认证用户访问返回404而非401/403

ASP.NET Identity Cookie认证Web API返回404而非401/403的解决办法

问题场景

使用ASP.NET Identity Cookie认证的ASP.NET Web API,当未认证/未授权用户访问受保护端点时,始终返回404(未找到)状态码,而非预期的401(未认证)或403(未授权),且业务不需要重定向功能。

尝试过的无效配置

  • 调用AddAuthentication().AddCookie()结合ConfigureApplicationCookie()配置,虽能正常设置Cookie名称,但配置AccessDeniedPath或自定义返回Unauthorized()的端点无法解决问题
  • 使用AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie()配置时,已登录用户的认证功能直接失效
  • 仅配置OnRedirectToAccessDenied事件设置状态码,仅解决了未授权用户返回403的问题,未认证用户仍返回404

最终解决方案

通过同时配置OnRedirectToAccessDenied和OnRedirectToLogin事件,分别为未授权、未认证场景设置对应的状态码,彻底解决问题。核心配置代码如下:

builder.Services.ConfigureApplicationCookie(config =>
{
    config.Cookie.Name = "Identity.Cookie";
    config.LoginPath = "/User/Login";
    config.LogoutPath = "/User/Logout";
    config.AccessDeniedPath = "/User/Login";
    
    config.Events.OnRedirectToAccessDenied = context =>
    {
        context.Response.StatusCode = (int)403;
        return Task.CompletedTask;
    };

    config.Events.OnRedirectToLogin = context =>
    {
        context.Response.StatusCode = (int)401;
        return Task.CompletedTask;
    };
});

内容的提问来源于stack exchange,提问作者Andrеw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 17:57:26