2

I am working on .Net CORE 3.1 web API. We use BackgroundHostedService to process time consuming operations. We need an access to HttpContext from that hosted service like this:

    public PermissionHelper(IHttpContextAccessor accessor)
    {
        var routeValue = accessor.HttpContext.GetRouteValue("tenantId");
    }

accessor.HttpContext is null here.

I tried to find a nice fix for that. One of them is to capture data inside a processing of HttpContext and pass that data to hostedservice. That method was described in Microsoft documentation: Access HttpContext in ASP.NET Core (Section - HttpContext access from a background thread)

It works fine. But it becomes a really big pain to do such fixes when you add a lot of different nuget packages to you project and those packages access HttContext (and all of that happens inside HostedService)

**My question: ** There is some better fix/workaround to make a "snapshot" of HttpContext inside Http request and pass that "snapshot" to hosted service?

Mahmoud Farahat
  • 5,364
  • 4
  • 43
  • 59
kihtov23
  • 131
  • 1
  • 7
  • 2
    That would make no sense. `HttpContext` refers to the context of a specific request and gets destroyed when that request ends. A background service has nothing to do with requests though. It lives far longer than any of them – Panagiotis Kanavos Oct 16 '20 at 09:59
  • 2
    It looks like what you need isn't the HttpContext at all but some specific information. Pass that to the background service along with the rest of the data it needs – Panagiotis Kanavos Oct 16 '20 at 10:00
  • 1
    Consider serializing the parts of the HttpContext that you need to a queue, and then having your background service reconstitute a custom HttpContext (BackgroundContext?) that you derive from HttpContext. Unlike traditional asp.net, asp.netcore's HttpContext is easy to derive from. From there, your BackgroundService can invoke the same middleware stack that your website is using; the stack won't know that the request came from a BackgroundService. – Eric Patrick May 08 '21 at 02:29

0 Answers0