Pergunta

I have nailed down a challenge for me which was the ability to log and continue/Inform a user about server exceptions when the request is ajax. Using the OnException in the base controller and looking for the request being ajax I can return a customized "...uhoh" view to be rendered.

Now, I am battling the not authenticated portion of stuff. I am struggling with this modified code I was thinking of using in place of the [Authorize] attribute in my base classes.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class AjaxAuthorizeAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult{Data = new{NotAuthenticated=1}, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
    }

Currently, there are a few areas where this could return NotAuthenticatedas data to the Ajax calls in the client. Am I going about this the right way? Just located the main flows that end in an Ajax.

if(returnData.NotAuthenticated){
    if (that.onNotAuthenticated != null)
       that.onNotAuthenticated();
    else
      _loadView(viewElement, "Request requires authorization. Please login again.");
} else
      _loadView(viewElement, returnData);
}

However, I am using the Kendo complete library and possibly others. Is there a better "Global" way to handle session timeouts or auth redirects when triggered via an Ajax call?

Please help!

Foi útil?

Solução

I think Global Ajax Event Handlers meets your needs. For example following code sets a global error handler which will redirect user to login page if her session is timeout.

$(document).ajaxError(function (event, jqxhr, settings, exception) {
    if (jqxhr.status == 401 || jqxhr.statusText == "Unauthorized") {
        window.location.href = '/login';
    }
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top