What is the most appropriate (and elegant?) way to pass boolean value of true or false through HttpResponse. I need it for a GetCustomerExist method (using ASP.NET Web API). Am writing it to the body of the message, but feel it's not the wright way of doing it. Can I pass it in the response header somehow?
Asked
Active
Viewed 3,731 times
1 Answers
2
Instead of creating a method that checks for the existence of a customer, a more "RESTful" way would be to send a HEAD
request to the customer resource. If the customer doesn't exist, answer with 404 Not Found
else with 200 OK
. In a HEAD
request, you don't have to provide the message body.
In a quick sample, I was able to implement this in WebAPI like this. In the sample, odd ids do exist, even ones return a 404. Also, I add a fantasy header value to the response:
public HttpResponseMessage Head(int id)
{
HttpResponseMessage msg;
if (id % 2 == 0)
msg = new HttpResponseMessage(HttpStatusCode.NotFound);
else
msg = new HttpResponseMessage(HttpStatusCode.OK);
msg.Headers.Add("Hello", "World");
return msg;
}

Markus
- 20,838
- 4
- 31
- 55
-
Do you have any link with exemplary implementation? Am struggling to make it work. Found this: http://www.strathweb.com/2013/03/adding-http-head-support-to-asp-net-web-api/ but when oldContent is assigned it runs into an error – Bartosz Apr 14 '14 at 16:25
-
@Bartosz: I've checked this in a small sample and added the relevant lines to the answer. – Markus Apr 14 '14 at 18:39
-
thanks for your help. How does the code on the other side looks like though? When I execute HttpWebResponse response = (HttpWebResponse)request.GetResponse(); I get an exeption "The remote server returned an error: (404) Not Found." Could base the logic on the exception but its not recommended as far as I'm aware – Bartosz Apr 15 '14 at 07:55
-
1@Bartosz: good to know that it helped. Unforunately I don't know a way other than catching the WebException and inspecting the StatusCode. See http://stackoverflow.com/questions/1949610/how-can-i-catch-a-404 and http://stackoverflow.com/questions/3771065/httpwebrequest-is-throwing-exception-for-404 (the latter provides an extension method so at least the code is a bit cleaner though the try-catch remains). – Markus Apr 15 '14 at 08:13