วิธีการดำเนินการของ Web API สามารถมีประเภทการส่งคืนดังต่อไปนี้
-
โมฆะ
-
ประเภทดั้งเดิม/ประเภทซับซ้อน
-
HttpResponseMessage
-
IHttpActionResult
โมฆะ −
ไม่จำเป็นว่าวิธีการดำเนินการทั้งหมดจะต้องส่งคืนบางสิ่ง สามารถมีประเภทการคืนเป็นโมฆะได้
ตัวอย่าง
using DemoWebApplication.Models
using System.Web.Http;
namespace DemoWebApplication.Controllers{
public class DemoController : ApiController{
public void Get([FromBody] Student student){
//Some Operation
}
}
}

วิธีการดำเนินการที่มีประเภทการส่งคืนเป็นโมฆะจะส่งคืน 204 ไม่มีเนื้อหา ตอบกลับ
ประเภทดั้งเดิม/ประเภทซับซ้อน −
วิธีการดำเนินการสามารถส่งคืนประเภทดั้งเดิม เช่น int, string หรือประเภทที่ซับซ้อน เช่น List เป็นต้น
ตัวอย่าง
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
public class DemoController : ApiController{
public List<string> Get([FromBody] Student student){
return new List<string>{
$"The Id of the Student is {student.Id}",
$"The Name of the Student is {student.Name}"
};
}
}
}

HttpResponseMessage −
ตัวอย่าง
HttpResponseMessage ใช้เมื่อเราต้องการกำหนดประเภทการส่งคืน (ผลการดำเนินการ) ของวิธีการดำเนินการเอง การตอบสนองได้รับการปรับแต่งโดยระบุรหัสสถานะ ประเภทเนื้อหา และข้อมูลที่จะส่งคืนไปยัง HttpResponseMessage
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, $"The Sudent Id is
{student.Id} and Name is {student.Name}");
} else {
return Request.CreateResponse(HttpStatusCode.BadRequest, $"InValid
Student Id");
}
}
}
}

ในตัวอย่างข้างต้น เราจะเห็นว่าการตอบกลับนั้นได้รับการปรับแต่ง เนื่องจากรหัสที่ส่งไปยังวิธีดำเนินการคือ 0 การดำเนินการอื่นจึงถูกดำเนินการและส่งคืนคำขอที่ไม่ถูกต้อง 400 รายการพร้อมข้อความแสดงข้อผิดพลาดที่ให้ไว้
IHttpActionResult −
ตัวอย่าง
อินเทอร์เฟซ IHttpActionResult ถูกนำมาใช้ใน Web API 2 โดยพื้นฐานแล้ว จะกำหนดโรงงาน HttpResponseMessage IHttpActionResult มีอยู่ในเนมสเปซ System.Web.Http ข้อดีของการใช้ IHttpActionResult บน HttpResponseMessage มีดังนี้
-
ลดความซับซ้อนของการทดสอบหน่วยควบคุมของคุณ
-
ย้ายตรรกะทั่วไปสำหรับการสร้างการตอบสนอง HTTP เป็นคลาสที่แยกจากกัน
-
ทำให้เจตนาของการดำเนินการควบคุมชัดเจนขึ้น โดยการซ่อนรายละเอียดระดับต่ำของการสร้างการตอบสนอง
ตัวอย่าง
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<string>{
$"The Id of the Student is {student.Id}",
$"The Name of the Student is {student.Name}"
};
return Ok(result);
}
}
}
