ASP.NET Web API에서 사용자 지정 서버 측 HTTP 메시지 처리기를 만들려면 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;
}
}
} DelegatingHandler에서 파생된 CustomMessageHandler 클래스를 선언했으며 그 안에서 SendAsync() 함수를 재정의했습니다.
HTTP 요청이 도착하면 CustomMessageHandler가 실행되고 HTTP 요청을 더 이상 처리하지 않고 자체적으로 하나의 HTTP 메시지를 반환합니다. 궁극적으로 우리는 모든 HTTP 요청이 상위 수준에 도달하는 것을 방지하고 있습니다.
3단계 -
이제 Global.asax 클래스에 CustomMessageHandler를 등록하십시오.
public class WebApiApplication : System.Web.HttpApplication{
protected void Application_Start(){
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.MessageHandlers.Add(new
CustomMessageHandler());
}
} 4단계 -
애플리케이션을 실행하고 URL을 제공하십시오.

위의 출력에서 우리는 ourCustomMessageHandler 클래스에 설정한 메시지를 볼 수 있습니다. 따라서 HTTP 메시지는 Get() 작업에 도달하지 않고 그 전에 CustomMessageHandler 클래스로 반환됩니다.