views:

33

answers:

1

My MVC web application serves two types of users. First one over standard web browser Second one over REST returning only Json data. Both requires 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 logIn 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 Unauthorized code 401 only.

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

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

and receive an 401 message.

The problem is that within mvc when i put the statusCode like this

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

it always redirect 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 get redirected to the log in page.

A: 

What you are experiencing is a hole in ASP.NET MVC (I hope they fix one day).

The standard operating model for ASP.NET is that if a 401 Http Status code is detected, then as you are experiencing, it automatically redirects to the login page, and this happens even if you have come in via an Ajax call. Unfortunately I have also not found any way to change this behaviour.

What I do instead is return an alternative, otherwise unused Http Status Code that I can detect in the client and handle in the appropriate manner.

Therefore within my Authentication Filter, if its an Ajax request I return 449 otherwise the standard 401. Then on the client I can examine the XMLHttpRequest.status and take appropriate action if 449 is detected.

Clicktricity