Asp.net Mvc custom mechanism to handle unauthorized request

Rusi Nova picture Rusi Nova · Aug 9, 2011 · Viewed 12.9k times · Source

For my website i want following behaviors for secured controller(or action)

if a user makes a normal request redirect to login page (which i have easily able to do)

if request is Ajax type Request.IsAjaxRequest()==true, return status code 401

How can i create a filter for this??

Answer

Praveen Prasad picture Praveen Prasad · Aug 9, 2011
 public class MyCustomAuthorize : AuthorizeAttribute
{
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //if ajax request set status code and end Response
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.StatusCode = 401;
                filterContext.HttpContext.Response.End();
            }

            base.HandleUnauthorizedRequest(filterContext);
        }
}

Create a filter like above, it will return status code 401 for unauthorized request if request is made thru ajax.

If you are using jQuery you can do as below

jQuery.ajax({
statusCode: {
    401: function() {
      alert('unauthrized');
    },

  /*other options*/
});