views:

72

answers:

1

Brief:

I have a sub classed AuthorizeAttribute in my framework in which I am doing custom authorization.

I am in the process of switching from normal asp.net mvc view rendering to Ajax rendering via jQuery. Hence every link in the application does a ajax call to get the data.

In order to cater for this I have converted most of my pages to partial views so that each ajax request only gets the portion that needs to be updated on the page.

During the normal view rendering when a request was unauthorized it was being redirected to the logon page described in the web.config. After converting to Ajax things are a bit different as I dont want the markup for the logon page in the ajax request but want a structured response in it so that I can act accordingly inside the ajax call.

In order to do this I believe I have to override the HandleUnauthorizedRequest method in the sub classed AuthorizeAttribute class and set the filterContext.Result to a json result. But in doing so how would I get to distinguish between a unauthorized request and a successfull request, because from the ajax calls point of view both are successful responses; hence will be handled in the success handler.

What would be the correct way to deal with this issue?

A: 

I have just figured it out, I can filter between normal requests and ajax requests in the HandleUnauthorized Request method that I override in my AuthorizeAttribute sub class. That way for an ajax request I can create a json result or something else for that matter, and for normal requests it would still show up the login page. the code is as follows:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            JsonResult UnauthorizedResult = new JsonResult();
            UnauthorizedResult.Data = "{ request : 'unauthorized' }";
            UnauthorizedResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            filterContext.Result = UnauthorizedResult;
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }

still I will not mark my question as resolved, so if someone can suggest a better way of doing it, I am still open to suggestions.

Nosh
Alright this is working out well during the session, as soon as the session expires the login page is again sent as a response to an ajax request the status of which is success. Hence I will have to do something to detect that the session has expired, has any one got any suggestions?
Nosh