当用户未登录时,我试图让ASP.NET Core Identity返回401.我已经[Authorize]
为我的方法添加了一个属性,而不是返回401,它返回302.我已经尝试了很多建议但是似乎没什么用,包括services.Configure
和app.UseCookieAuthentication
设置LoginPath
为null
或PathString.Empty
.
从ASP.NET Core 2.x开始:
services.ConfigureApplicationCookie(options => { options.Events.OnRedirectToLogin = context => { context.Response.StatusCode = 401; return Task.CompletedTask; }; });
如果请求标头包含X-Requested-With:XMLHttpRequest,则状态代码将为401而不是302
private static bool IsAjaxRequest(HttpRequest request) { return string.Equals(request.Query["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) || string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal); }
请参阅gitHub:https://github.com/aspnet/Security/blob/5de25bb11cfb2bf60d05ea2be36e80d86b38d18b/src/Microsoft.AspNetCore.Authentication.Cookies/Events/CookieAuthenticationEvents.cs#L40-L52
对于Asp.net Core 2,请 使用此安装程序
services.ConfigureApplicationCookie(options => { options.LoginPath = new PathString("/Account/Login"); options.LogoutPath = new PathString("/Account/Logout"); options.Events.OnRedirectToLogin = context => { if (context.Request.Path.StartsWithSegments("/api") && context.Response.StatusCode == StatusCodes.Status200OK) { context.Response.Clear(); context.Response.StatusCode = StatusCodes.Status401Unauthorized; return Task.CompletedTask; } context.Response.Redirect(context.RedirectUri); return Task.CompletedTask; }; });