When making a request using $.ajax()
, I typically do it like this:
$.ajax({
type: "GET",
url: myUrl
success: function(data) {
$("#replace").html(data)
},
error: function (data) {
console.warn(data);
}
});
Another way is to attach handlers to the promises of the ajax call:
$.ajax({
type: "GET",
url: myUrl
})
.done(function(data, status) {
console.log(data);
})
.fail(function(data, status) {
console.warn(status);
});
In both scenarios, the error/fail function is triggered when there's an HTTP status error.
In my ASP.NET MVC project, I want to return the proper HTTP Status Code. This is important from a semantic perspective and for accurate handling on the client side.
Attempt #1 - Following advice provided in this answer, I tried returning 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 in this answer, I attempted returning a JsonResult
while 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();
Despite these efforts, the response still indicates 200 OK.
https://i.sstatic.net/jEy2K.png
Questions:
- Is it correct that an AJAX response should include an Unauthorized status code?
- Do I need to set this value elsewhere as well?
- Are there server-level configurations that need adjustment to allow non-200 status codes?
This issue discussed in Always success on ajax post with HttpResponseMessage 401 seems similar but lacks a clear solution at the server side level, resorting instead to accepting the OK error status code and inspecting responses for errors manually.