A message handler is a class that receives an HTTP request and returns an HTTP response.
Typically, a series of message handlers are chained together. The first handler receives an HTTP request, does some processing, and gives the request to the next handler. At some point, the response is created and goes back up the chain. This pattern is called a delegating handler.
這樣做有什麼好處呢
我們從中處理拿到的資料 或是紀錄我們之間傳輸的值 我們就不必傻傻的在每個controller或是其他地方寫相同的邏輯 這時候我們就可以透過這種方式做處理
簡單說如下圖
public class RequestAndResponseLoggerDelegatingHandler : DelegatingHandler { public IDataAccess Data { get; set; } protected override async Task最後我們在註冊到我剛剛所寫的方法 當然也可以註冊很多層SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { var started = DateTime.UtcNow; var requestContent = await request.Content.ReadAsStringAsync(); var response = await base.SendAsync(request, cancellationToken); var responseContent = await response.Content.ReadAsStringAsync(); await Log(started, request, response, requestContent, responseContent); return response; } private async Task Log(DateTime start, HttpRequestMessage request, HttpResponseMessage response, string requestContent, string responseContent) { var finished = DateTime.UtcNow; var info = new ApiLogEntry(start, finished, requestContent, responseContent, request, response); Data.Log(info); } }
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MessageHandlers.Add(new RequestAndResponseLoggerDelegatingHandler1()); config.MessageHandlers.Add(new RequestAndResponseLoggerDelegatingHandler2()); // Other code not shown... } }或者是我們在WebApiConfig綁定 特定的路徑 這都是不錯的處理方式
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "Route1", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "Route2", routeTemplate: "api2/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: null, handler: new MessageHandler2() // per-route message handler ); config.MessageHandlers.Add(new MessageHandler1()); // global message handler } }參考連結
https://stackoverflow.com/questions/27176329/web-api-request-content-empty
https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers
沒有留言:
張貼留言