Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Authorize ajax call in MVC

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 478
    Comment on it

    Hi All,

    In many of our scenario's we intent to make ajax calls to get or post data. What if the session logged off before you made the ajax call, what will and should happen in this scenario. What will happen is the call will never be completed and nothing will be shown over the page. What should happen is the user should be notified that he has logged off and will need to login again to perform that particular action, the same that happens when we submit our form.

    How will we make the user notified in ajax call?
    Below is a simple and quick way of doing that.

    Step 1 - We will override default HandleUnauthorizedRequest:

    public class ApplicationAuthorizeAttribute : AuthorizeAttribute
    {
    	protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    	{
    		var httpContext = filterContext.HttpContext;
    		var request = httpContext.Request;
    		var response = httpContext.Response;
    
    		if (request.IsAjaxRequest())
    		{
    			response.StatusCode = (int)HttpStatusCode.Unauthorized;
    
    			response.SuppressFormsAuthenticationRedirect = true;
    			response.End();
    		}
    
    		base.HandleUnauthorizedRequest(filterContext);
    	}
    }

    Step 2 - Will use 

     [ApplicationAuthorize]

    instead of

    [Authorize]

    attribute, as ApplicationAuthorizeAttribute inherits AuthorizeAttribute it will work as [Authorize] but one additional advantage will be regarding Unauthorized Request from ajax.

    Step 3 - From where we are intended to make the ajax call we will add a small code snippet for error handling:

    error: function (xhr, ajaxOptions, thrownError) {
    if (xhr.status == 401) {
    	alert("You are logged Off. Please Login Again...")
    	window.location = "/Account/Login";
    }

    This will authorize your ajax calls and will send you to login page if you are logged off.

    Happy Coding....

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: