In ASP.NET Web API, the return type of an action method can vary depending on the desired response format. Here, we will cover few examples of common return types used in ASP.NET Web API.
The Web API action method can have following return types.
1. Void
It's not necessary that all action methods must return something. It can have void return type. Consider the following Delete action method that just deletes the employee from the data source and returns nothing.
Example
public class EmployeeController : ApiController
{
public void Delete(int empid)
{
DeleteEmployeeFromDB(empid);
}
}
2. Primitive or Complex Type
An action method can return primitive or other custom complex types as other normal methods.
Consider the following Get action methods.
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public class EmployeeController : ApiController
{
public int GetId(string name)
{
int id = GetEmployeeId(name);
return id;
}
public Employee GetEmployee(int id)
{
var employee = GetEmployeeFromDB(id);
return employee;
}
}
As you can see above, GetId action method returns an integer and GetEmployee action method returns a Student type.
An HTTP GET request http://localhost:xxxx/api/employee?name=Rohatash will return following response in Fiddler.
An HTTP GET request http://localhost:xxxx/api/employee?id=1 will return following response in Fiddler.
3. IHttpActionResult
The IHttpActionResult interface is a common return type in ASP.NET Web API. It allows you to return various types of responses, such as OkNegotiatedContentResult, BadRequestErrorMessageResult, NotFoundResult, and more.
Example
public IHttpActionResult Get()
{
var data = // retrieve data from a source
if (data != null)
{
return Ok(data); // 200 OK response with the data
}
else
{
return NotFound(); // 404 Not Found response
}
}
4. HttpResponseMessage
You can also return an HttpResponseMessage object directly. This provides more control over the response, allowing you to set the status code, headers, and content.
Example
public HttpResponseMessage Get()
{
var data = // retrieve data from a source
if (data != null)
{
return Request.CreateResponse(HttpStatusCode.OK, data); // 200 OK response with the data
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Data not found"); // 404 Not Found response with an error message
}
}
5. Custom Data Types
Action methods can return custom data types as well. For example, you can define a class to represent the response data and return an instance of that class.
public class MyDataResponse
{
public string Name { get; set; }
public int Age { get; set; }
}
public MyDataResponse Get()
{
var data = // retrieve data from a source
if (data != null)
{
return new MyDataResponse { Name = data.Name, Age = data.Age };
}
else
{
return null;
}
}