Blazor Server App - Problem with accessing request scope in DelegatingHandler · Issue #57481 · dotnet/aspnetcore (original) (raw)
Is there an existing issue for this?
- I have searched the existing issues
Describe the bug
I have a problem with getting request scope in blazor server app.
I use HttpClientFactory
to communitace with one of my services. I wanted to inject dynamic header into each request.
To do so I created custom DelegatingHandler
.
Because HttpClient
handlers are created in a separate scope (https://andrewlock.net/understanding-scopes-with-ihttpclientfactory-message-handlers/) I took the approach with injecting IHttpContextAccessor
.
Here is draft of the handler:
public class MyHeaderHandler : DelegatingHandler
{
private readonly IHttpContextAccessor _httpContextAccessor;
public MyHeaderHandler(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var prov = _httpContextAccessor?.HttpContext?.RequestServices.GetService(typeof(IMyProvider)) as IMyProvider;
...
}
}
IMyProvider
(registered as scoped service in DI) instance has some data set during request processing. I need to access that data.
The problem is that the instance I get from IHttpContextAccessor
from MyHeaderHandler
is different from the instance I get in blazor components or other services used there directly (not via DelegatingHandler
).
I tried to set SuppressHandlerScope option to true, but no luck:
serviceCollection.Configure<HttpClientFactoryOptions>(builder.Name, options =>
{
options.SuppressHandlerScope = true;
});
AFAIK this approach works in WebApi projects and the problem is with Blazor apps.
To me it looks like a BUG.
If this method of getting request scope is not correct, I would be more than happy to get some advice here.
Expected Behavior
IHttpContextAccessor.HttpContext.RequestServices gives access to request scope.
Steps To Reproduce
No response
Exceptions (if any)
No response
.NET Version
8.0.304
Anything else?
No response