ASP.NETCore如何返回401而不是302?我正在尝试让ASP.NETCoreIdentity在用户未登录时返回401。我已将[Authorize]属性添加到我的方法中,而不是返回401,而是返回302。我已经尝试了很多建议,但似乎没有任何效果,包括services.Configure和app.UseCookieAuthentication将LoginPath设置为null或PathString.Empty。从ASP.NETCore2.x开始:services.ConfigureApplicationCookie(options=>{options.Events.OnRedirectToLogin=context=>{context.Response.StatusCode=401;returnTask.CompletedTask;};});services.Configure(options=>{options.Cookies.ApplicationCookie.LoginPath=newPathString("/");options.Cookies.ApplicationCookie.Events=newCookieAuthenticationEvents(){OnRedirectToLogin=context=>{if(context.Request.Path.Value.StartsWith("/api")){context.Response.Clear();context.Response.StatusCode=401;returnTask.FromResult(0);}context.Response.Redirect(context.RedirectUri);返回任务.FromResult(0);}};});资源:https://www.illucit.com/blog/2016/04/asp-net-5-identity-302-redirect-vs-401-unauthorized-for-api-ajax-requests/如果请求标头包含X-Requested-With:XMLHttpRequest,则状态代码将为401而不是302铝)||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.netCore2,请使用此安装程序服务。ConfigureApplicationCookie(options=>{options.LoginPath=newPathString("/Account/Login");options.LogoutPath=newPathString("/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;returnTask.FromResult(null);}}context.Response.Redirect(context.RedirectUri);returnTask.FromResult(null);};});好吧,在深入研究asp.net核心单元测试之后,我终于找到了一个可行的解决方案你必须在调用services.AddIdentity时添加以下内容以上是C#学习教程:如何在ASP.NETCore中返回401而不是302?分享的所有内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——services.AddIdentity(o=>{o.Cookies.ApplicationCookie.AutomaticChallenge=false;});本文来自网络收藏,不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
