I was getting HttpContext.Current as null inside the method which is called inside a task factory. So I assigned the HttpContext.Current to currentContext variable. Then I used the same variable to assign HttpContext.Current.
var currentContext = HttpContext.Current;
Task shipmentCreationCompleted = Task.Factory.StartNew(() =>
{
HttpContext.Current = currentContext;
MethodToPerformSomeAction();
});
It is now working fine without any problem. Please let me know if my code has any problem technically. Or is there any alternate way to handle this problem?
The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.
HttpContext isn't thread-safe. Reading or writing properties of the HttpContext outside of processing a request can result in a NullReferenceException.
HttpContext encapsulates all information about an individual HTTP request and response. An HttpContext instance is initialized when an HTTP request is received. The HttpContext instance is accessible by middleware and app frameworks such as Web API controllers, Razor Pages, SignalR, gRPC, and more.
Finally i used like this based on the comment,
Task shipmentCreationCompleted = Task.Factory.StartNew(currentContext =>
{
HttpContext.Current = (HttpContext)currentContext;
MethodToPerformSomeAction();
}, HttpContext.Current);
It works great!
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