开发者

How to handle UnauthorizedRequest via Ajax call in Asp.net MVC2

开发者 https://www.devze.com 2023-01-08 19:07 出处:网络
Brief: I have a sub classed AuthorizeAttribute in my framework in which I am doing custom authorization.

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 acc开发者_如何学运维ordingly 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号