Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
545 views
Welcome To Ask or Share your Answers For Others

1 Answer

Because a status of 200 is being returned, but the user is not authorized, another option is to check for X-Responded-JSON with a status of 401 in your javascript.

.done(function (object, status, xhr) {
      if (xhr.getResponseHeader("X-Responded-JSON") != null 
          && JSON.parse(xhr.getResponseHeader("X-Responded-JSON")).status == "401") {
          //some message here
          return;
     }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...