■ HttpClientBuilderExtensions 클래스의 AddHttpMessageHandler 확장 메소드를 사용해 위임 처리기를 만들기
▶ Handlers/SecureRequestHandler.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 |
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace TestProject.Handlers { /// <summary> /// 보안 요청 핸들러 /// </summary> public class SecureRequestHandler : DelegatingHandler { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 송신하기 (비동기) - SendAsync(request, cancellationToken) /// <summary> /// 송신하기 (비동기) /// </summary> /// <param name="httpRequestMessage">HTTP 요청 메시지</param> /// <param name="cancellationToken">취소 토큰</param> /// <returns>HTTP 응답 메시지 태스크</returns> protected override Task<HttpResponseMessage> SendAsync ( HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken ) { if(httpRequestMessage.RequestUri.Scheme == Uri.UriSchemeHttp) { UriBuilder uriBuilder = new UriBuilder(httpRequestMessage.RequestUri) { Scheme = Uri.UriSchemeHttps }; httpRequestMessage.RequestUri = uriBuilder.Uri; } return base.SendAsync(httpRequestMessage, cancellationToken); } #endregion } } |
▶ Handlers/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 Microsoft.Extensions.Logging; using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; 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 } } |
▶ Startup.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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using TestProject.Handlers; namespace TestProject { /// <summary> /// 시작 /// </summary> public class Startup { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구성 - Configuration /// <summary> /// 구성 /// </summary> public IConfiguration Configuration { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Startup(configuration) /// <summary> /// 생성자 /// </summary> /// <param name="configuration">구성</param> public Startup(IConfiguration configuration) { Configuration = configuration; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스 컬렉션 구성하기 - ConfigureServices(services) /// <summary> /// 서비스 컬렉션 구성하기 /// </summary> /// <param name="services">서비스 컬렉션</param> public void ConfigureServices(IServiceCollection services) { services.AddTransient<SecureRequestHandler>(); services.AddTransient<RequestDataHandler>(); services.AddHttpClient("test") // 이 핸들러는 외부에 있으며 요청 중에 먼저 호출되고 응답 중에 마지막으로 호출된다. .AddHttpMessageHandler<SecureRequestHandler>() // 이 핸들러는 전송되는 요청에 가장 가까운 내부에 있다. .AddHttpMessageHandler<RequestDataHandler>(); services.AddControllersWithViews(); } #endregion #region 구성하기 - Configure(app, environment) /// <summary> /// 구성하기 /// </summary> /// <param name="app">애플리케이션 빌더</param> /// <param name="environment">웹 호스트 환경</param> public void Configure(IApplicationBuilder app, IWebHostEnvironment environment) { if(environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints ( endpoints => { endpoints.MapControllerRoute ( name : "default", pattern : "{controller=Home}/{action=Index}/{id?}" ); } ); } #endregion } } |
※ 위임 처리기를 사용하는 코드는 없으며 설정하는 코드만 있는 예제이다.