Phương thức hành động Web API có thể có các kiểu trả về sau:
- Void
- Primitive Type / Complex Type
- HttpResponseMessage
- IHttpActionResult
Void
Không bắt buộc tất cả action methods phải trả về giá trị. Có thể dùng kiểu void.
Ví dụ
using DemoWebApplication.Models;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public void Get([FromBody] Student student)
{
// Some Operation
}
}
}

Action method với kiểu void sẽ trả về phản hồi 204 No Content.
Primitive Type / Complex Type
Action method có thể trả về kiểu nguyên thủy như int, string hoặc kiểu phức tạp như List.
Ví dụ
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public List Get([FromBody] Student student)
{
return new List
{
$"Id của Student là {student.Id}",
$"Tên của Student là {student.Name}"
};
}
}
}

HttpResponseMessage
HttpResponseMessage dùng khi muốn tùy chỉnh kiểu trả về (action result) của action method. Response được tùy chỉnh bằng cách cung cấp status code, content type, và dữ liệu trả về cho HttpResponseMessage.
Ví dụ
using DemoWebApplication.Models;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public HttpResponseMessage Get([FromBody] Student student)
{
if (student.Id > 0)
{
return Request.CreateResponse(HttpStatusCode.OK,
$"Id của Student là {student.Id} và Tên là {student.Name}");
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest, "Student Id không hợp lệ");
}
}
}
}

Trong ví dụ trên, response được tùy chỉnh. Vì Id gửi đến là 0, block else thực thi và trả về 400 Bad Request với thông báo lỗi.
IHttpActionResult
Interface IHttpActionResult được giới thiệu trong Web API 2. về cơ bản nó định nghĩa một HttpResponseMessage factory. IHttpActionResult nằm trong namespace System.Web.Http. Ưu điểm so với HttpResponseMessage:
- Đơn giản hóa unit testing cho controllers
- Di chuyển logic chung tạo HTTP responses vào các class riêng biệt
- Làm rõ ý định của controller action, ẩn chi tiết cấp thấp xây dựng response
Ví dụ
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public IHttpActionResult Get([FromBody] Student student)
{
var result = new List
{
$"Id của Student là {student.Id}",
$"Tên của Student là {student.Name}"
};
return Ok(result);
}
}
}
