HttpContext.Current is null when adding delegate handlerHttpContext.Current.Session is null in Ashx fileHTTP handler vs HTTP moduleWhy is HttpContext.Current null after await?ASP.Net vs MVC vs WebAPI and UseTaskFriendlySynchronizationContextHow should I log performance parameters to Sql Server Database (possibly using NLog)Thread Static, ASP.NET and Async handlersWeb API Service - How to use “HttpContext.Current” inside async taskApproach for tying all NLog logs back to the original request within WebAPI?NLog MappedDiagnosticsLogicalContext not working in async/await with ConfigureAwait(false)ASP.Net WebApi Rest Service - using Task.Factory.StartNewApplication logging with ELK stack

Binary Search in C++17

Windows 10 Programs start without visual Interface

At what point in European history could a government build a printing press given a basic description?

Does revoking a certificate result in revocation of its key?

Employer asking for online access to bank account - Is this a scam?

Why is this Simple Puzzle impossible to solve?

Where is the logic in castrating fighters?

Rename photos to match video titles

Would jet fuel for an F-16 or F-35 be producible during WW2?

What is the largest (size) solid object ever dropped from an airplane to impact the ground in freefall?

Logarithm of dependent variable is uniformly distributed. How to calculate a confidence interval for the mean?

What does the view outside my ship traveling at light speed look like?

How strong are Wi-Fi signals?

General purpose replacement for enum with FlagsAttribute

Looking for a soft substance that doesn't dissolve underwater

Does this degree 12 genus 1 curve have only one point over infinitely many finite fields?

Can't remember the name of this game

Approximate solution: factorial and exponentials

Crossing US border with music files I'm legally allowed to possess

Canon 70D often overexposing or underexposing shots

What is the most important source of natural gas? coal, oil or other?

Rests in pickup measure (anacrusis)

Python program to convert a 24 hour format to 12 hour format

Is there a public standard for 8 and 10 character grid locators?



HttpContext.Current is null when adding delegate handler


HttpContext.Current.Session is null in Ashx fileHTTP handler vs HTTP moduleWhy is HttpContext.Current null after await?ASP.Net vs MVC vs WebAPI and UseTaskFriendlySynchronizationContextHow should I log performance parameters to Sql Server Database (possibly using NLog)Thread Static, ASP.NET and Async handlersWeb API Service - How to use “HttpContext.Current” inside async taskApproach for tying all NLog logs back to the original request within WebAPI?NLog MappedDiagnosticsLogicalContext not working in async/await with ConfigureAwait(false)ASP.Net WebApi Rest Service - using Task.Factory.StartNewApplication logging with ELK stack






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-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










share|improve this question






















  • this is what you looking for (?) : stackoverflow.com/questions/14181408/…

    – Aristos
    Mar 24 at 10:03












  • Works fine for me. Could you please provide relevant code of your handler and controller?

    – Alexander
    Mar 24 at 11:54











  • Thanks @Alexander I got solution. Please see my proposed answer

    – Kamran Asim
    Mar 25 at 5:22

















-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










share|improve this question






















  • this is what you looking for (?) : stackoverflow.com/questions/14181408/…

    – Aristos
    Mar 24 at 10:03












  • Works fine for me. Could you please provide relevant code of your handler and controller?

    – Alexander
    Mar 24 at 11:54











  • Thanks @Alexander I got solution. Please see my proposed answer

    – Kamran Asim
    Mar 25 at 5:22













-1












-1








-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










share|improve this question














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







asp.net asp.net-web-api nlog httphandler






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 24 at 7:25









Kamran AsimKamran Asim

49628




49628












  • this is what you looking for (?) : stackoverflow.com/questions/14181408/…

    – Aristos
    Mar 24 at 10:03












  • Works fine for me. Could you please provide relevant code of your handler and controller?

    – Alexander
    Mar 24 at 11:54











  • Thanks @Alexander I got solution. Please see my proposed answer

    – Kamran Asim
    Mar 25 at 5:22

















  • this is what you looking for (?) : stackoverflow.com/questions/14181408/…

    – Aristos
    Mar 24 at 10:03












  • Works fine for me. Could you please provide relevant code of your handler and controller?

    – Alexander
    Mar 24 at 11:54











  • Thanks @Alexander I got solution. Please see my proposed answer

    – Kamran Asim
    Mar 25 at 5:22
















this is what you looking for (?) : stackoverflow.com/questions/14181408/…

– Aristos
Mar 24 at 10:03






this is what you looking for (?) : stackoverflow.com/questions/14181408/…

– Aristos
Mar 24 at 10:03














Works fine for me. Could you please provide relevant code of your handler and controller?

– Alexander
Mar 24 at 11:54





Works fine for me. Could you please provide relevant code of your handler and controller?

– Alexander
Mar 24 at 11:54













Thanks @Alexander I got solution. Please see my proposed answer

– Kamran Asim
Mar 25 at 5:22





Thanks @Alexander I got solution. Please see my proposed answer

– Kamran Asim
Mar 25 at 5:22












1 Answer
1






active

oldest

votes


















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.TicksThread.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);








share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55321591%2fhttpcontext-current-is-null-when-adding-delegate-handler%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    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.TicksThread.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);








    share|improve this answer



























      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.TicksThread.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);








      share|improve this answer

























        0












        0








        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.TicksThread.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);








        share|improve this answer













        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.TicksThread.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);









        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 25 at 5:22









        Kamran AsimKamran Asim

        49628




        49628





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55321591%2fhttpcontext-current-is-null-when-adding-delegate-handler%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현