Action Method Return Type

Action Method Return Type:



Action Method Return Type:

Ở trong phần trước , bạn đã tìm hiểu về ràng buộc tham só với phương thức Web API. Bài này , bạn sẽ tìm hiểu về kiểu dữ liệu trả về của nhưng phương thức mà lần lượt được nhúng vào trong response Web API gửi đến phía Client.
Phương thức Web API có thể có những kiểu dữ liệu trả về sau
  1. Void
  2. Primitive type or Complex type
  3. HttpResponseMessage
  4. IHttpActionResult

Void:

Không nhất phải những phương thức này phải trả về một cái gì đó. Nó nó thể có kiểu trả về là void
Ví dụ ,xem xét phương thức Delete sau mà chỉ xóa Student từ nguồn dữ liệu và không trả về gì cả. 
Example: Void Return Type

public class StudentController : ApiController
{
    public void Delete(int id)
    {
        DeleteStudentFromDB(id);
    }
}

Như bạn thấy ở trên phương thức Delete trả về void. Nó sẽ gửi trạng thái code 204 "No content" như là một lời phản hồi khi bạn gửi request HTTP Delete.
Void Response Status

Primitive or Complex Type:

Phương thức có thể trả về kiểu dữ liệu nguyên thủy hoặc kiểu phức tạp tùy biến như những phương thức bình thường khác.
Consider the following Get action methods.
Example: Primitive or Complex Return Type

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class StudentController : ApiController
{
    public int GetId(string name)
    {
        int id = GetStudentId(name);
    
        return id;
    }

    public Student GetStudent(int id)
    {
        var student = GetStudentFromDB(id);
    
        return student;
    }
}

Như bạn thấy ở trên , phương thức GetId trả về một kiểu dữ liệu integer và phương thức GetStudent trả về một đối tượng kiểu Student.

Một request Http Get http://localhost:xxx/api/student?name=john sẽ trả về phản hồi sau trong phần Fiddler.
Primitive Return Type in Response
An HTTP GET request http://localhost:xxxx/api/student?id=1 will return following response in Fiddler.
Complex Return Type in Response

HttpResponseMessage:

Web API controller luôn luôn trả về một đối tượng kiểu
HttpResponseMessage . Hình sau sẽ mô tả tổng thể Web API request/response.
Web API Request Pipeline
Visit Web API HTTP Message Life Cycle Poster for more details.
Như bạn thấy trong hình trên , Web API controller trả về đối tượng
HttpResponseMessage.
Lợi ích của việc gửi HttpResponseMessage từ một phương thức là bạn có thể cấu hình theo cách của bạn. Bạn có thể gán trạng thái code , nội dung trả về hoặc thông báo lỗi (nếu có) theo yêu cầu của bạn
Consider the following example.
Example: Return HttpResponseMessage
 
public HttpResponseMessage Get(int id)
{
    Student stud = GetStudentFromDB(id); 

    if (stud == null) {
        return Request.CreateResponse(HttpStatusCode.NotFound, id);
    }

    return Request.CreateResponse(HttpStatusCode.OK, stud);
}  

Trong phương thức trên . Nếu không có student nào với id được chỉ định trong DB thì nó sẽ trả về trạng thái mã là 404 Not Found , ngược lại nó sẽ trả về trạng thái mã là 200 OK với dữ liệu student
For example, an http GET request http://localhost:xxxx/api/student?id=100 will get following response considering student with id=100 does not exists in the DB.
Web API Response in Fiddler
The same way, an HTTP GET request http://localhost:60464/api/student?id=1 will get following response considering student with id=1 exists in the database .
Web API Response in Fiddler

IHttpActionResult:

The IHttpActionResult was introduced in Web API 2 (.NET 4.5). An action method in Web API 2 can return an implementation of IHttpActionResult class which is more or less similar to ActionResult class in ASP.NET MVC.
You can create your own class that implements IHttpActionResult or use various methods of ApiController class that returns an object that implement the IHttpActionResult.
Example: Return IHttpActionResult Type using Ok() and NotFound() Methods

public IHttpActionResult Get(int id)
{
    Student stud = GetStudentFromDB(id);
            
    if (stud == null)
    {
        return NotFound();
    }

    return Ok(stud);
}

In the above example, if student with specified id does not exists in the database then it will return response with the status code 404 otherwise it sends student data with status code 200 as a response. As you can see, we don't have to write much code because NotFound() and Ok() method does it all for us.
The following table lists all the methods of ApiController class that returns an object of a class that implements IHttpActionResult interface.
ApiController MethodDescription
BadRequest()Creates a BadRequestResult object with status code 400.
Conflict()Creates a ConflictResult object with status code 409.
Content()Creates a NegotiatedContentResult with the specified status code and data.
Created()Creates a CreatedNegotiatedContentResult with status code 201 Created.
CreatedAtRoute()Creates a CreatedAtRouteNegotiatedContentResult with status code 201 created.
InternalServerError()Creates an InternalServerErrorResult with status code 500 Internal server error.
NotFound()Creates a NotFoundResult with status code404.
Ok()Creates an OkResult with status code 200.
Redirect()Creates a RedirectResult with status code 302.
RedirectToRoute()Creates a RedirectToRouteResult with status code 302.
ResponseMessage()Creates a ResponseMessageResult with the specified HttpResponseMessage.
StatusCode()Creates a StatusCodeResult with the specified http status code.
Unauthorized()Creates an UnauthorizedResult with status code 401.
Visit MSDN to know all the members of ApiController.

Create Custom Result Type:

You can create your own custom class as a result type that implements IHttpActionResult interface.
The following example demonstrates implementing IHttpActionResult class.
Example: Create Custom Result Type

public class TextResult : IHttpActionResult
{
    string _value;
    HttpRequestMessage _request;

    public TextResult(string value, HttpRequestMessage request)
    {
        _value = value;
        _request = request;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage()
        {
            Content = new StringContent(_value),
            RequestMessage = _request
        };
        return Task.FromResult(response);
    }
}

Now, you can return TextResult object from the action method as shown below.
Example: Return Custom Result Type

public IHttpActionResult GetName(int id)
{
    string name = GetStudentName(id);
            
    if (String.IsNullOrEmpty(name))
    {
        return NotFound();
    }
            
    return new TextResult(name, Request);
}

Nhận xét

Bài đăng phổ biến từ blog này

Web API : Parameter Binding

Web API Routing