|
| 1 | +using Microsoft.AspNetCore.Builder; |
| 2 | +using Microsoft.Extensions.DependencyInjection; |
| 3 | +using SW.PrimitiveTypes; |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Linq; |
| 7 | +using System.Runtime.CompilerServices; |
| 8 | +using System.Text; |
| 9 | + |
| 10 | +namespace SW.HttpExtensions |
| 11 | +{ |
| 12 | + public static class IAppBuilderExtensions |
| 13 | + { |
| 14 | + |
| 15 | + public static IApplicationBuilder UseHttpUserRequestContext(this IApplicationBuilder applicationBuilder) |
| 16 | + { |
| 17 | + |
| 18 | + applicationBuilder.Use(async (httpContext, next) => |
| 19 | + { |
| 20 | + if (httpContext.User.Identity.IsAuthenticated) |
| 21 | + { |
| 22 | + var vals = new List<RequestValue>(); |
| 23 | + |
| 24 | + foreach (var h in httpContext.Request.Headers) |
| 25 | + vals.Add(new RequestValue(h.Key, string.Join(";", h.Value.ToArray()), RequestValueType.HttpHeader)); |
| 26 | + |
| 27 | + foreach (var q in httpContext.Request.Query) |
| 28 | + //if (!ignoredKeys.Contains(q.Key, StringComparer.OrdinalIgnoreCase)) |
| 29 | + vals.Add(new RequestValue(q.Key, string.Join(";", q.Value.ToArray()), RequestValueType.QueryParameter)); |
| 30 | + |
| 31 | + string correlationId = Guid.NewGuid().ToString("N"); |
| 32 | + |
| 33 | + if (httpContext.Request.Headers.TryGetValue("request-correlation-id", out var cid) && cid.Count > 0) |
| 34 | + correlationId = cid.First(); |
| 35 | + |
| 36 | + var requestContext = httpContext.RequestServices.GetRequiredService<RequestContext>(); |
| 37 | + |
| 38 | + requestContext.Set(httpContext.User, vals, correlationId); |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | + |
| 43 | + await next(); |
| 44 | + }); |
| 45 | + |
| 46 | + return applicationBuilder; |
| 47 | + |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments