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

Categories

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

json - how can mvc return Unauthorized code without redirecting to LogIn view

My MVC web application serves two types of users.

  • First one over standard web browser;
  • Second one over REST returning only JSON data.

Additionally,

  • Both require Authentication and authorization;
  • Both scenarios are differentiated based on the route so that I know what content to serve.

When users access the application, if they are not logged in, the application should react differently.

  1. In the first case it should return the default LogIn page (this is fine).
  2. In the second case it should return a 401 Unauthorized code only.

I'm used to working with WCF REST service where I could raise an exception like this:

throw new WebProtocolException(System.Net.HttpStatusCode.Unauthorized, exc.Message, exc);

and receive a 401 message. The problem with the same approach within MVC when I put the statusCode like this:

HttpContext.Response.StatusCode = (Int32)HttpStatusCode.Unauthorized

it always redirects to the LogIn page.

How can I do this?

I've tried overriding the AuthorizeAttribute and handling the OnAuthorization function, but still as soon as I set the statusCode to 401 it gets redirected to the LogIn page.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

To prevent login page redirection you must set SuppressFormsAuthenticationRedirect property of HttpContext.Response to true;

 HttpContext.Response.SuppressFormsAuthenticationRedirect = true;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...