-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
  • 670
  • 4
  • 16

1 Answers1

1

Thanks @Alexander,

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

For reference below is my DelegatingHandler implementation. Before this I defined two methods i.e. IncomingMessageAsync(), 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
        IncomingMessageAsync(request);
        var response = await base.SendAsync(request, cancellationToken);
        context.Items["responseTime"] = DateTime.Now;
        HttpContext.Current = context;
        OutgoingMessageAsync(response);
        return response;
    }

    protected void IncomingMessageAsync(HttpRequestMessage request)
    {
        logger.Info("Request received from {URL}", request.Method + " " + request.RequestUri);
    }

    protected void OutgoingMessageAsync(HttpResponseMessage response)
    {
        if (response.IsSuccessStatusCode)
        {
            logger.Info("Response returned with status {Status}", response.StatusCode);
        }
        else
        {
            logger.Warn("Response returned with status {Status}", response.StatusCode);
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kamran Asim
  • 670
  • 4
  • 16