Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...