■ DelegatingHandler 클래스를 사용해 데이터 요청 핸들러를 만드는 방법을 보여준다.
▶ RequestDataHandler.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace TestProject.Handlers { /// <summary> /// 데이터 요청 핸들러 /// </summary> public class RequestDataHandler : DelegatingHandler { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 로그 기록기 /// </summary> private readonly ILogger<RequestDataHandler> logger; /// <summary> /// 요청 소스 헤더명 /// </summary> private const string RequestSourceHeaderName = "Request-Source"; /// <summary> /// 요청 소스 /// </summary> private const string RequestSource = "TestProject"; /// <summary> /// 요청 ID 헤더명 /// </summary> private const string RequestIDHeaderName = "Request-Identifier"; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - RequestDataHandler(logger) /// <summary> /// 생성자 /// </summary> /// <param name="logger">로그 기록기</param> public RequestDataHandler(ILogger<RequestDataHandler> logger) { this.logger = logger; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 송신하기 (비동기) - SendAsync(httpRequestMessage, cancellationToken) /// <summary> /// 송신하기 (비동기) /// </summary> /// <param name="httpRequestMessage">HTTP 요청 메시지</param> /// <param name="cancellationToken">취소 토큰</param> /// <returns>HTTP 응답 메시지 태스크</returns> protected override Task<HttpResponseMessage> SendAsync ( HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken ) { Guid identifierGUID = Guid.NewGuid(); this.logger.LogInformation("Starting request {Identifier}", identifierGUID); httpRequestMessage.Headers.Add(RequestSourceHeaderName, RequestSource ); httpRequestMessage.Headers.Add(RequestIDHeaderName , identifierGUID.ToString()); return base.SendAsync(httpRequestMessage, cancellationToken); } #endregion } } |