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;
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
add a comment |
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
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
add a comment |
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
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
asp.net asp.net-web-api nlog httphandler
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
add a comment |
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
add a comment |
1 Answer
1
active
oldest
votes
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);
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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);
add a comment |
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);
add a comment |
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);
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);
answered Mar 25 at 5:22
Kamran AsimKamran Asim
49628
49628
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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