I'm submitting a standard $.ajax()
request like this:
$.ajax({
type: "GET",
url: myUrl
success: function(data) {
$("#replace").html(data)
},
error: function (data) {
console.warn(data);
}
});
Or the same thing by attaching the handler to the ajax promise callbacks like this:
<!-- language: lang-js -->$.ajax({
type: "GET",
url: myUrl
})
.done(function(data, status) {
console.log(data);
})
.fail(function(data, status) {
console.warn(status);
});
In both cases, or when using $.ajaxError()
handler, the error/fail function is called when a HTTP status error is returned.
In my ASP.NET MVC project, I'm trying to return the proper HTTP Status Code, both for semantic reasons and to be caught by the right client side handler.
Attempt #1 - As suggested by this answer I've tried to return a HttpStatusCodeResult
like this:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized, accessResult.AccessDeniedMessage);
filterContext.HttpContext.Response.End();
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
Attempt #2 - Alternatively, as suggested by this answer, I've tried returning a JsonResult
and also setting the Response.StatusCode
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
filterContext.Result = new JsonResult()
{
Data = new { Error = "Unauthorized User" },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.HttpContext.Response.End();
In both cases, the response still comes back as 200 OK
Questions:
- Am I correct about the semantics that I should be returning an AJAX response with a Unauthorized Status Code?
- Is there somewhere else to set this value that I need to do also?
- Is there some server level setting to allow non-200 status codes to be returned?
This question on Always success on ajax post with HttpResponseMessage 401 seems to be running into the same error, but doesn't propose a server side solution, instead just allowing the OK error status code and scraping the response to determine if an error occurred.