I have built a WebAPI (using version 2) that returns HttpResponseMessage. I make AJAX requests to these WebAPI methods, and the WebAPI returns a JSON response. This is all fine and dandy, but now what I need is a way to make an AJAX GET request to a WebAPI method that simply returns a Boolean. Here's an example of a GET request I'm using to get JSON:
$.ajax({
url: 'http://server/site/api/BulletinBoard/GetUserMessageHistory?userId=' + userId + '&messageId=' + messageId,
type: 'GET',
dataType: 'json',
crossDomain: true,
success: function (data) {
DoSomething();
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
What I hope to accomplish is something like (this is pseudo-code):
var hasMessageBeenDisplayed =
$.ajax({
url: 'http://server/site/api/BulletinBoard/GetUserMessageHistory?userId=' + userId + '&messageId=' + messageId,
type: 'GET',
dataType: 'json',
crossDomain: true,
success: function (data) {
DoSomething();
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
Where hasMessageBeenDisplayed would be either true or false returned by my WebAPI method. Here's an example of my WebAPI method:
[HttpGet]
public HttpResponseMessage GetUserMessageHistory(string userId, int messageId)
{
var userMessageHistory = (from i in db.UserMessageHistories
where i.UserId == userId &&
i.MessageId == messageId
select new
{
UserId = i.UserId,
MessageId = i.MessageId,
LastSeen = i.LastSeen,
}).ToList();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, userMessageHistory);
return response;
}
To be able to make an AJAX request that expects true or false, would I still return HttpResponseMessage from my WebAPI method? How can I make an AJAX GET request whose method it's calling can return true or false?
$.ajax()return theXMLHttpRequest, if the webapi return 200 status code, it will execute thesuccessevent of your call. Since you set thejsonin the ajax call, you are sending the request to webapi with the content-typeapplication/jsonand you will get an output in this format.