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.
- In the first case it should return the default LogIn page (this is fine).
- 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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…