Disable Not Authorized Redirect to Account/Login in ASP.NET Core

旧街凉风 提交于 2019-11-28 07:51:07

问题


I have a set of WebAPI services in a shared library. These are used in an ASP.NET Core MVC Web Site and dedicated server only hosting the WebAPI Services without the MVC component.

Everything works as expected on the MVC Web Site with Unauthorized Requests, I get the 304 redirect to the login page (Account/Login). However when I make an unauthorized request to the WebAPI services, I receive the same 304 redirect to /Account/Login in this case I would like to return the Http 401 Unauthorized result code. I would prefer to not handle this in a custom AuthorizeAttribute but would rather handle at the site level in my Startup class.


回答1:


I suspect you have registered ASP.NET Core Identity with both your MVC (Views) Part as well as with your WebApi part.

You must separate it and the CookieMiddleware (one registered inside .UseIdentity() call) must only be registered for request to your MVC pages, but not for your WebAPI calls.

You can use the .Map or MapWhen methods (see docs).

// For requests not going to WebAPI controllers
app.MapWhen(context => !context.Request.Path.StartsWithSegments("/api"), branch =>
{
    branch.UseIdentity();
});


来源:https://stackoverflow.com/questions/43455395/disable-not-authorized-redirect-to-account-login-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!