Before reading this post, Please go through the previous post on Web API
What is the asp.net Web API-part-1
CRUD operation in Asp.net web-api-part-2
How to test Web API-part-3
In asp.net web api action method can have the following return type
1. Void
2. Primitive type or Complex type
3. HttpResponseMessage
4. IHttpActionResult
1. Void
// DELETE api/values/5 public void Delete(int id) { tblEmp tblEmp = db.tblEmps.Find(id); db.tblEmps.Remove(tblEmp); db.SaveChanges(); }
2. Primitive type or Complex type
public int GetId() { return 10; }
public tblEmp GetEmpDetail(int id) { tblEmp objEmp = db.tblEmps.Find(id); return objEmp; }
3. HttpResponseMessage:
HttpResponseMessage allows us to work with the HTTP protocol. It is the way of returning Http Response Message from the Action Method.
public HttpResponseMessage GetEmpDetail(int id) { tblEmp objEmp = db.tblEmps.Find(id); if (objEmp != null) { return Request.CreateResponse(HttpStatusCode.OK, objEmp); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, " Employee Not Found"); } }
3. IHttpResponseMessage:
IHttpActionResult interface is the new approach to write the action method in Asp.net Web API. It came in Asp.net Web API 2.0.
Here are some advantages of using the IHttpActionResult interface:
>> Simplifies unit testing your controllers.
>> Moves common logic for creating HTTP responses into separate classes.
>> Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.