-
Notifications
You must be signed in to change notification settings - Fork 10
/
ConversationIdProviderMiddleware.cs
49 lines (43 loc) · 1.76 KB
/
ConversationIdProviderMiddleware.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
namespace Todo.WebApi.Logging
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
/// <summary>
/// Provides conversation IDs to each request to allow grouping them into conversations.
/// </summary>
// ReSharper disable once ClassNeverInstantiated.Global
public class ConversationIdProviderMiddleware
{
private const string ConversationId = "ConversationId";
private readonly RequestDelegate nextRequestDelegate;
private readonly ILogger logger;
public ConversationIdProviderMiddleware(RequestDelegate nextRequestDelegate,
ILogger<ConversationIdProviderMiddleware> logger)
{
this.nextRequestDelegate =
nextRequestDelegate ?? throw new ArgumentNullException(nameof(nextRequestDelegate));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task Invoke(HttpContext httpContext)
{
if (!httpContext.Request.Headers.TryGetValue(ConversationId, out StringValues conversationId)
|| string.IsNullOrWhiteSpace(conversationId))
{
conversationId = Guid.NewGuid().ToString("N");
httpContext.Request.Headers.Add(ConversationId, conversationId);
}
httpContext.Response.Headers.Add(ConversationId, conversationId);
using (logger.BeginScope(new Dictionary<string, object>
{
[ConversationId] = conversationId.ToString()
}))
{
await nextRequestDelegate(httpContext);
}
}
}
}