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

how can mvc return Unauthorized code without redirecting to LogIn view


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

 HttpContext.Response.SuppressFormsAuthenticationRedirect = true;


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.


You can create a simple authorization attribute filter (extend the AuthorizeAttribute class) and use it for your access control. Then try something like this:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext){    if (filterContext.HttpContext.Request.IsAjaxRequest() ||  string.Compare("GET", filterContext.HttpContext.Request.HttpMethod, true) != 0)    {        // Returns 403.        filterContext.Result = new HttpStatusCodeResult((int)HttpStatusCode.Forbidden);    }    else    {        // Returns 401.        filterContext.Result = new HttpUnauthorizedResult();    }}

The effect is that, POST and AJAX requests will always receive a 403 response which makes it easier for you to handle your ajax submits in javascript. As for the non-ajax posts, it doesn't really matter what the response is because your user shouldn't have got his hands on the submit form in the first place :)

As for the other requests, the method returns 401 that the formsAuthentiction module will pick up and then redirect your response to the login page.