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.
$(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.