-1

In one of my project I had added delegate handler to log incoming and outgoing requests. For Logging I am using Nlog. I was generating a unique Id, per request to relate logs with this specific Id. This worked fine for me. Now recently I modified my code in handler, and set HttpContext.Currnet.Item value to this unique id. Now I am supposed to get this id, and pass it to external Apis.

Issue I faced is inside controller HttpContext.Current is null. I know what is the main root cause. This is because of handler.SendAsync, which will make the thread SynchronizationContext as null.

I want to pass HttpContext.Current to my ongoing threads.

What I did:

I set ConfigureAwait(false) I set appsettings -> aspnet:UseTraskFriendlySynchronizationContext to true

but these are not working.

I am using .net framework 4.7.1

Kamran Asim
  • 650
  • 3
  • 13

1 Answers1

0

Thanks @Alexander, After your comments I reviewed my code again and found this problem is not caused by await base.SendAsync(), Infact I was calling internal methods with async, which ruined HttpContext.Current.

For reference bellow is my DelegatingHandler Implementation. Before this I defined two methods i.e. IncommingMessageAsync(), OutgoingMessageAsync as Async. Now I had changed it to simple methods. Because I don't want Task in these methods.

 public  class MessageHandler : DelegatingHandler
{
    private static NLog.Logger logger;
    HttpContext context;

    public MessageHandler()
    {
        logger = NLog.LogManager.GetCurrentClassLogger();
    }
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var correlationID = $"{DateTime.Now.Ticks}{Thread.CurrentThread.ManagedThreadId}";
        context = HttpContext.Current;
        context.Items["correlationID"] = correlationID;     //used in Nlog aspnet-item:variable=correlationID
        IncommingMessageAsync(request);
        var response = await base.SendAsync(request, cancellationToken);
        context.Items["responseTime"] = DateTime.Now;
        HttpContext.Current = context;
        OutgoingMessageAsync(response);
        return response;
    }
    protected void IncommingMessageAsync(HttpRequestMessage request)
    {
        logger.Info("Request Received from {URL}", request.Method + " " + request.RequestUri);
    }
    protected void OutgoingMessageAsync(HttpResponseMessage response)
    {
        if (response.IsSuccessStatusCode)
        {
            logger.Info("Resposne Returned with Status {Status}", response.StatusCode);
        }
        else
        {
            logger.Warn("Resposne Returned with Status {Status}", response.StatusCode);
        }
    }
}
Kamran Asim
  • 650
  • 3
  • 13