/// <summary> /// Sets the correlation id on IOwinRequest and IOwinResponse. If the Owin.RequestId already exists a new one will not be generated. /// Only if the Owin.RequestId is null, empty, whitespace, or non-existent will it be overriden. /// </summary> /// <param name="context">The <see cref="IOwinContext"/>.</param> /// <param name="createCorrelationId">The Func to build a correlation ID.</param> /// <param name="requestIdName">The name of the Http Header to place the request correlation id.</param> public static void SetCorrelationId(this IOwinContext context, CorrelationIdProperties properties) { var correlationId = properties.GenerateId(); var requestIdName = properties.CorrelationIdHeaderName; var environment = context.Environment; // Update IOwinContext.Environment if it doesn't have a value. var hasCorrelationId = environment.ContainsKey(OwinRequestIdKey) && !string.IsNullOrWhiteSpace(environment[OwinRequestIdKey].ToString()); if (hasCorrelationId) { correlationId = environment[OwinRequestIdKey].ToString(); } else { environment[OwinRequestIdKey] = correlationId; } // Apply correlation ID to Request and Response. var headerValue = new[] { correlationId }; if (context.Request.Headers.ContainsKey(correlationId)) { context.Request.Headers[requestIdName] = correlationId; } else { context.Request.Headers.Add(requestIdName, headerValue); } context.Response.Headers.Add(requestIdName, headerValue); }
/// <summary> /// Use request correlation middleware. Adds a Request ID to the Request and Response. /// </summary> /// <param name="app">The app.</param> /// <param name="properties">The properties for the request correlation.</param> /// <returns>The <see cref="IAppBuilder"/>.</returns> public static IAppBuilder UseRequestIds(this IAppBuilder app, CorrelationIdProperties properties = null) { if (properties == null) { properties = new CorrelationIdProperties(); } app.Use <RequestIdMiddleware>(properties); return(app); }
/// <summary> /// Initializes a new instance of <see cref="RequestIdMiddleware"/>. /// </summary> /// <param name="next">The next owin middleware to execute.</param> /// <param name="properties">The <see cref="CorrelationIdProperties"/> used to configure the middleware.</param> public RequestIdMiddleware(OwinMiddleware next, CorrelationIdProperties properties) : base(next) { _properties = properties; }