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

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

c# - Always success on ajax post with HttpResponseMessage 401

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

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

1 Answer

0 votes
by (71.8m points)

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;
     }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...