Welcome to OStack Knowledge Sharing 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...