I am trying to access the Request
property in my ApiController
-derived class.
For some reason, Request
is null in ExecuteAsync
method. I've seen the other questions, so before you ask:
ExecuteAsync
method, my request passes through a delegating handler, and in the delegating handler, my request object exists (I even add some properties without any problem).return await base.SendAsync(request, cancellationToken);
without a problem and request
exists.HttpContext.Current.Request
is not null and accessible without problem.RequestContext
is not null and accessible without problem.Request
is null.Why would this occur? I'm on Web API 2.2 (and MVC 5, if relevant).
This is probably due to the fact that you're trying to access HttpContext while working with async/await.
So, you have two options:
You can read more here - Using HttpContext Safely After Async in ASP.NET MVC Applications.
To better understand what's going on under the hood, I'd recommend:
In a very very high level: in a synchronous server implementations, where the entire request is processed by the same thread, the execution context is stored using TLS (thread local storage), means HttpContext is available anywhere in your code.
In an asynchronous server implementation (async/await), the request may be processed by several threads, and there's a need to pass the execution context between those threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With