tclarkston
tclarkston

Reputation: 161

Web API and jQuery ajax not receiving correct error

I am trying to use a jQuery ajax to call a web api method. Using very basic methods I can not get the ajax call to return the proper response. I have tried multiple ways thinking that it may be the response but with no luck.

Here is my code:

Web API

 // POST api/token
 public Token Post(User user)
 {
      throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));  
 }

jQuery

  $.ajax({
        url: http://myUrl/api/token',
        type: 'POST',
        dataType: 'json',
        data: data,
        success: function () {
        },
        error: function (request, status, error) {
            alert(request.status);
            //request.status is always 0, I am expecting 401
        }
    });

I have also tried using:

 .done(function() {
 })
 .fail(function(data) {
     //status code is always 0 instead of expected 401
  });

and:

 statusCode: {
      401: function () {
      //Never gets hit
      },
 }

When I check the response using Firebug in FF, I am receiving the correct response in the console:

 POST http://myUrl/api/token 401 Unauthorized

So either the satus code is always 0 or the 401 statusCode: is never hit. What am I doing wrong and/or what do I need to do in order to properly catch the 401 error on the client?

Upvotes: 0

Views: 3106

Answers (4)

madan
madan

Reputation: 1

Try this:

public Token Post([forms body]User user)
{
  throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));  
 }

Upvotes: 0

tclarkston
tclarkston

Reputation: 161

I finally found the problem. $.ajax didn't like the cross domain call. Once I added "Access-Control-Allow-Origin: *" to the response header of my REST POST method, then I was able to get the correct data.

Upvotes: 1

Rod
Rod

Reputation: 1

Try this:

var result = $.ajax({
    url: http://myUrl/api/token',
    type: 'POST',
    dataType: 'json',
    data: data,
    success: function () {
    },
    error: function (request, status, error) {
        alert(request.status);
        //request.status is always 0, I am expecting 401
    }
});

var statusCode = result.status;

or alternatively:

$.ajax({
    url: http://myUrl/api/token',
    type: 'POST',
    dataType: 'json',
    data: data,
    success: function (result) {
        alert(result.status);
    },
    error: function (request, status, error) {
        alert(request.status);
        //request.status is always 0, I am expecting 401
    }
});

Upvotes: 0

Vladimir
Vladimir

Reputation: 7475

Try this:

public Token Post(User user)
{
    Request.CreateResponse(HttpStatusCode.Unauthorized);
}

Upvotes: 0

Related Questions