ในการสร้างตัวจัดการข้อความ HTTP ฝั่งเซิร์ฟเวอร์ที่กำหนดเองใน ASP.NET Web API เราจำเป็นต้องสร้างคลาสที่ต้องได้รับมาจาก System.Net.Http.DelegatingHandler .
ขั้นตอนที่ 1 -
สร้างตัวควบคุมและวิธีการดำเนินการที่เกี่ยวข้อง
ตัวอย่าง
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
public class StudentController : ApiController{
List<Student> students = new List<Student>{
new Student{
Id = 1,
Name = "Mark"
},
new Student{
Id = 2,
Name = "John"
}
};
public IEnumerable<Student> Get(){
return students;
}
public Student Get(int id){
var studentForId = students.FirstOrDefault(x => x.Id == id);
return studentForId;
}
}
} ขั้นตอนที่ 2 -
สร้างคลาส CutomerMessageHandler ของเราเอง
ตัวอย่าง
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace DemoWebApplication{
public class CustomMessageHandler : DelegatingHandler{
protected async override Task<HttpResponseMessage>
SendAsync(HttpRequestMessage request, CancellationToken cancellationToken){
var response = new HttpResponseMessage(HttpStatusCode.OK){
Content = new StringContent("Result through custom message handler..")
};
var taskCompletionSource = new
TaskCompletionSource<HttpResponseMessage>();
taskCompletionSource.SetResult(response);
return await taskCompletionSource.Task;
}
}
} เราได้ประกาศคลาส CustomMessageHandler ที่ได้มาจาก DelegatingHandlerand ซึ่งเราได้แทนที่ฟังก์ชัน SendAsync()
เมื่อคำขอ HTTP มาถึง CustomMessageHandler จะดำเนินการและจะส่งคืนข้อความ HTTP หนึ่งข้อความด้วยตัวเอง โดยไม่ต้องประมวลผลคำขอ HTTP เพิ่มเติม แท้จริงแล้วเรากำลังป้องกันไม่ให้คำขอ HTTP แต่ละรายการไปถึงระดับที่สูงกว่า
ขั้นตอนที่ 3 -
ตอนนี้ลงทะเบียน CustomMessageHandler ในคลาส Global.asax
public class WebApiApplication : System.Web.HttpApplication{
protected void Application_Start(){
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.MessageHandlers.Add(new
CustomMessageHandler());
}
} ขั้นตอนที่ 4 -
เรียกใช้แอปพลิเคชันและระบุ URL

จากผลลัพธ์ข้างต้น เราจะเห็นข้อความที่เราตั้งไว้ในคลาส CustomMessageHandler ของเรา ดังนั้นข้อความ HTTP จะไม่ไปถึงการดำเนินการ Get() และก่อนหน้านั้นข้อความดังกล่าวจะกลับไปยังคลาส CustomMessageHandler ของเรา