且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从ASP.NET Core Webapi中删除重定向并返回HTTP 401?

更新时间:2023-02-15 08:28:49

我在Angular2 + ASP.NET Core应用程序中遇到了此问题.我设法通过以下方式对其进行了修复:

I had with this problem in an Angular2 + ASP.NET Core application. I managed to fix it in the following way:

services.AddIdentity<ApplicationUser, IdentityRole>(config =>   {
    // ...
    config.Cookies.ApplicationCookie.AutomaticChallenge = false;
    // ...
});

如果这不适用于您,则可以尝试使用以下方法:

If this is not working for you, you can try with the following method instead:

services.AddIdentity<ApplicationUser, IdentityRole>(config =>   {
    // ...
    config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
    {
       OnRedirectToLogin = ctx =>
       {
           if (ctx.Request.Path.StartsWithSegments("/api")) 
           {
               ctx.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
               // added for .NET Core 1.0.1 and above (thanks to @Sean for the update)
               ctx.Response.WriteAsync("{\"error\": " + ctx.Response.StatusCode + "}");
           }
           else
           {
               ctx.Response.Redirect(ctx.RedirectUri);
           }
           return Task.FromResult(0);
       }
    };
    // ...
}

Asp.Net Core 2.0更新

现在可以通过以下方式配置Cookie选项:

Cookie options are now configured in the following way:

services.ConfigureApplicationCookie(config =>
            {
                config.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = ctx => {
                        if (ctx.Request.Path.StartsWithSegments("/api"))
                        {
                            ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        }
                        else {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                        return Task.FromResult(0);
                    }
                };
            });