Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Return Type ของ Controller Action ใน C# ASP.NET WebAPI มีอะไรบ้าง

Web API Action Method รองรับ Return Type 4 แบบ:

  • Void
  • Primitive Type / Complex Type
  • HttpResponseMessage
  • IHttpActionResult

1. Void

ไม่จำเป็นต้อง Return ค่า จะส่ง Response 204 No Content

public void Get([FromBody] Student student)
{
    // Some operation
}

Return Type ของ Controller Action ใน C# ASP.NET WebAPI มีอะไรบ้าง

2. Primitive/Complex Type

Return int, string, List, Object ตรงๆ Web API จะ Serialize ให้อัตโนมัติ

public List Get([FromBody] Student student)
{
    return new List
    {
        $"The Id of the Student is {student.Id}",
        $"The Name of the Student is {student.Name}"
    };
}

Return Type ของ Controller Action ใน C# ASP.NET WebAPI มีอะไรบ้าง

3. HttpResponseMessage

ควบคุม Response เต็มรูปแบบ (Status Code, Content, Headers)

public HttpResponseMessage Get([FromBody] Student student)
{
    if (student.Id > 0)
    {
        return Request.CreateResponse(HttpStatusCode.OK,
            $"The Student Id is {student.Id} and Name is {student.Name}");
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Student Id");
    }
}

Return Type ของ Controller Action ใน C# ASP.NET WebAPI มีอะไรบ้าง

4. IHttpActionResult (Web API 2+)

Factory สำหรับสร้าง HttpResponseMessage ข้อดี: ทดสอบง่าย แยก Logic Response ออกไป แยก Low-level Details

public IHttpActionResult Get([FromBody] Student student)
{
    var result = new List
    {
        $"The Id of the Student is {student.Id}",
        $"The Name of the Student is {student.Name}"
    };
    return Ok(result); // Helper method สร้าง IHttpActionResult
}

Return Type ของ Controller Action ใน C# ASP.NET WebAPI มีอะไรบ้าง