In this article we will see HTTP Response Message as return type for the API method. This is part three of the article series. Before reading this article, I would recommend reading the following previous parts.
HTTPResponseMessage feature is provided by WebAPI framework which is used to create HTTP services. It helps us to send responses in different ways. HTTPResponse message is used to return data as well as some user friendly messages like:
Status Code Status Message
200 OK
201 Created
404 Not Found

HTTPResponseMessage in Web API

Now let’s see step by step implementation of HTTPResponseMessage:
  1. namespace HTTPResponseMessage.Controllers
  2. {
  3. public class ServiceController: ApiController
  4. {
  5. static List < string > serviceData = LoadService();
  6. public static List < string > LoadService()
  7. {
  8. return new List < string > ()
  9. {
  10. "Mobile Recharge",
  11. "Bill Payment"
  12. };
  13. }
  14. // GET: api/Service
  15. public HttpResponseMessage Get()
  16. {
  17. return Request.CreateResponse < IEnumerable < string >> (HttpStatusCode.OK, serviceData);
  18. }
  19. // GET: api/Service/5
  20. public HttpResponseMessage Get(int id)
  21. {
  22. if (serviceData.Count > id) return Request.CreateResponse < string > (HttpStatusCode.OK, serviceData[id]);
  23. else return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Item Not Found");
  24. }
  25. // POST: api/Service
  26. public HttpResponseMessage Post([FromBody] string value)
  27. {
  28. serviceData.Add(value);
  29. return Request.CreateResponse(HttpStatusCode.Created, "Item Added Successfully");
  30. }
  31. // PUT: api/Service/5
  32. public HttpResponseMessage Put(int id, [FromBody] string value)
  33. {
  34. serviceData[id] = value;
  35. return Request.CreateResponse(HttpStatusCode.OK, "Item Updated Successfully");
  36. }
  37. // DELETE: api/Service/5
  38. public HttpResponseMessage Delete(int id)
  39. {
  40. serviceData.RemoveAt(id);
  41. return Request.CreateResponse(HttpStatusCode.OK, "Item Deleted Successfully");
  42. }
  43. }
  44. }
Run your application and follow below steps:

GET
GET By ID
POST
PUT
DELETE
Next >> All About API: HTTP Verb Attributes - Part Four