■ DelegatingHandler 클래스를 사용해 헤더 검증 핸들러를 만드는 방법을 보여준다.
▶ ValidateHeaderHandler.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 |
using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace TestProject { /// <summary> /// 헤더 검증 핸들러 /// </summary> public class ValidateHeaderHandler : DelegatingHandler { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 송신하기 (비동기) - SendAsync(request, cancellationToken) /// <summary> /// 송신하기 (비동기) /// </summary> /// <param name="httpRequestMessage">HTTP 요청 메시지</param> /// <param name="cancellationToken">취소 토큰</param> /// <returns>HTTP 응답 메시지 태스크</returns> protected override async Task<HttpResponseMessage> SendAsync ( HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken ) { if(!httpRequestMessage.Headers.Contains("X-API-KEY")) { return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("You must supply an API key header called X-API-KEY") }; } return await base.SendAsync(httpRequestMessage, cancellationToken); } #endregion } } |