سؤال

I am using ajax unobtrusive and when it gets to my custom authorization tag the status code is set and I have json data ready to go but when its returning the information the status code is caught in the console and saying for example,"Failed to load resource: the server responded with a status of 403(forbidden)." I placed alerts in the onfailure ajax option and nothing is being fired there. It seems its not considering a statuscode error as a failure ajax call. How can I handle the status code error in the onFailure ajax option?

                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    var urlHelper = new UrlHelper(filterContext.RequestContext);
                    filterContext.HttpContext.Response.StatusCode = 403;
                    filterContext.Result = new JsonResult()
                    {
                        Data = new
                        {
                            Error = "NotAuthorized",
                            LogOnUrl = urlHelper.Action("AccessDenied", "Error", new { area=""})
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }

This is in my custom authorize attribute.

@Ajax.ActionLink("Company", "Company", "Admin", null, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "centerAdmin", HttpMethod = "POST", OnComplete = "Oncomplete", OnSuccess = "OnSuccess", OnFailure = "OnFailure" })

my Ajax unobtrusive call

<script>

function OnSuccess(ajaxContext)
{
    alert("dfgsdfgsdfgsdfgfdgsdfgddf");
}
function OnFailure(ajaxContext) {
    alert("dfgsdfsdfgdfgsgsdf");
}
function Oncomplete(ajaxContext) {
    alert("dfgsddfffffffffffffffffffffgsdf");
}

simple alerts to see if it fired any of these events.

هل كانت مفيدة؟

المحلول 2

$(function () {
$(document).ajaxError(function (e, xhr) {
    debugger;
    if (xhr.status == 403) {
        alert("403");
    }
    alert("not 403");
});

});

After researching a bit, I came across this code snippet which seems to solve my issue for now.

نصائح أخرى

Since you are probably tired of me answering your questions with more questions, here is something to try. It should at least fall in to your OnFailure handler. Instead of setting your Result to a json object, set it to an HttpStatusCodeResult.

filterContext.Result = new HttpStatusCodeResult((int)HttpStatusCode.Forbidden, "You are not authorized to access this page!"); // Set whatever status code is appropriate.

Not sure about passing the logon url or other json parameters, but this should be a start. I don't think you need to set the status code of the response.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top