|
| 1 | +using System; |
| 2 | +using System.Net.Http; |
| 3 | +using System.Threading.Tasks; |
| 4 | + |
| 5 | +using Microsoft.AspNetCore.Http; |
| 6 | + |
| 7 | +namespace Azure.WebJobs.Extensions.HttpApi |
| 8 | +{ |
| 9 | + public abstract class ProxyFunctionBase |
| 10 | + { |
| 11 | + protected ProxyFunctionBase(IHttpClientFactory httpClientFactory, IHttpContextAccessor httpContextAccessor) |
| 12 | + { |
| 13 | + _httpClient = httpClientFactory.CreateClient(); |
| 14 | + _httpContextAccessor = httpContextAccessor; |
| 15 | + } |
| 16 | + |
| 17 | + private readonly HttpClient _httpClient; |
| 18 | + private readonly IHttpContextAccessor _httpContextAccessor; |
| 19 | + |
| 20 | + protected async Task SendAsync(string destinationPrefix) |
| 21 | + { |
| 22 | + var context = _httpContextAccessor.HttpContext; |
| 23 | + |
| 24 | + var request = new HttpRequestMessage(); |
| 25 | + |
| 26 | + request.Method = GetHttpMethod(context.Request.Method); |
| 27 | + |
| 28 | + foreach (var (name, value) in context.Request.Headers) |
| 29 | + { |
| 30 | + request.Headers.TryAddWithoutValidation(name, (string)value); |
| 31 | + } |
| 32 | + |
| 33 | + var response = await _httpClient.SendAsync(request); |
| 34 | + } |
| 35 | + |
| 36 | + private static HttpMethod GetHttpMethod(string method) |
| 37 | + { |
| 38 | + return method switch |
| 39 | + { |
| 40 | + { } when HttpMethods.IsGet(method) => HttpMethod.Get, |
| 41 | + { } when HttpMethods.IsPost(method) => HttpMethod.Post, |
| 42 | + { } when HttpMethods.IsPut(method) => HttpMethod.Put, |
| 43 | + { } when HttpMethods.IsDelete(method) => HttpMethod.Delete, |
| 44 | + { } when HttpMethods.IsOptions(method) => HttpMethod.Options, |
| 45 | + { } when HttpMethods.IsHead(method) => HttpMethod.Head, |
| 46 | + { } when HttpMethods.IsPatch(method) => HttpMethod.Patch, |
| 47 | + _ => throw new ArgumentOutOfRangeException(nameof(method), method, null) |
| 48 | + }; |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments