This question already has answers here:
</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/20149750/unauthorised-webapi-call-returning-login-page-rather-than-401" dir="ltr">Unauthorised webapi call returning login page rather than 401</a>
<span class="question-originals-answer-count">
(15 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2016-10-14 22:22:43Z" class="relativetime">3 years ago</span>.</div>
</div>
</aside>
I have a issue regarding exception throwing and catching on client side. This has all worked well until I introduced HTTP401. This is my base controler than overrides OnExcpetion:
protected override void OnException(ExceptionContext filterContext)
{
var exception = HandleException.Handle(filterContext.Exception);
filterContext.Exception = exception;
if(exception is AuthenticationException)
filterContext.HttpContext.Response.StatusCode = 401;
else
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult()
{
Data = new { Message = filterContext.Exception.Message },
ContentType = "json"
};
}
This is my AJAX call along with succes and error.
$.ajax(
{
type: 'POST',
url: loginRoute,
data: formData,
dataType: 'json',
processData: false,
contentType: false,
statusCode: {
401: function () {
$('#authenticationErrorMessage').text(xhr.responseJSON.Message);
$('#authenticationError').show();
}
},
success: function (responseData) {
$('#authenticationSucessMessage').text(responseData.Message);
$('#authenticationSuccess').show();
window.location.replace(responseData.Redirect);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#authenticationErrorMessage').text(xhr.responseJSON.Message);
$('#authenticationError').show();
}
});
The problems is that neither status code nor error are called upon completion. Only success is called. If I set my StatusCode to 500 all works fine.
</div>