Quick tip if you want to read the HTTP headers from the incoming GraphQL request in .NET Core using HotChocolate.
There are 2 ways I found that can be used to achieve this:
- Inject the IHttpContextAccessor in your resolvers.
- Create a custom Query Interceptor and set the context data
First one is rather obvious but let’s see an example on how to take the second approach:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services.AddQueryRequestInterceptor((ctx, builder, ct) => | |
{ | |
var headers=ctx.Response.Headers; | |
builder.SetProperty("Culture", headers["culture"]); | |
return Task.CompletedTask; | |
}); |
In your resolvers you can now access the context property through the ContextData directly or by injecting it:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public Task<string> MyResolver([State("Culture")]string culture) | |
{ | |
//Removed other code | |
} |