Skip to content Skip to sidebar Skip to footer

How To Use Custom Authorizeattribute With Ajax

With help of fellow friends I managed to find a solution for my problem from this topic: Reusable way to allow an account to be used by a single person at a time I have a SingleLog

Solution 1:

You can handle errors on AJAX request this way

$.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify({ message: input }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        if (data.messageSaved) {
            $("#txtMsg").val("");
        }
        else {
            window.location.href = urlhome;
        }
    },
    error: function(xhr, status, error) {
        // TODO: may be check error or status or xhr.statusCode()window.location.href = urlhome;
    }
});

jQuery $.ajax() docs

Solution 2:

If understand it correctly you want to handle the unauthorized ajax request.

In that case you can override the HandleUnauthorizedRequest method in your attribute:

protectedoverridevoidHandleUnauthorizedRequest(AuthorizationContext filterContext){
    if (filterContext.HttpContext.Request.IsAjaxRequest()) 
    {
        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
        filterContext.Result = newJsonResult();
    }
    else
    {
        filterContext.Result = newHttpStatusCodeResult((int)HttpStatusCode.Forbidden);
    }
}

Post a Comment for "How To Use Custom Authorizeattribute With Ajax"