I always get statusCode=200
on ajax post at client side, while servers answers with HttpStatusCode.Unauthorized
.
My controller code:
public class AccountApiController : ApiController
{
public HttpResponseMessage Login(HttpRequestMessage request, [FromBody]LoginViewModel loginModel)
{
return request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized login.");
}
}
My ajax code:
$.ajax({
url: '/api/accountapi/login',
type: 'POST',
data: data
})
.done(function (object, status, xhr) {
alert("Success: " + xhr.status + " : " + xhr.statusText);
})
.always(function (object) {
$("#output").text(JSON.stringify(object, null, 4));
});
Result: alert with text Success: 200 : OK
and output window with:
{
"Message": "Unauthorized login."
}
So, I can get text error message, but i need to get HttpStatusCode to handle error statements. Help me, please.
More information about this issue and elegant solution from Brock Allen:
http://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…