Luc*_*lip 0 entity-framework-core graphql hotchocolate
我正在尝试使用 hotchocolate 提高 sql 查询性能。为此,我想在应用程序的另一层访问 hotchololate 生成的查询请求。我能找到的唯一方法是拦截请求,将我需要的信息存储在 HttpContext 项中,然后在我需要的地方注入 IHttpContextAccessor。
services.AddQueryRequestInterceptor(GraphQLRequestInterceptor);
...
private Task GraphQLRequestInterceptor(HttpContext context, IQueryRequestBuilder requestBuilder, CancellationToken cancellationToken)
{
IReadOnlyQueryRequest request = requestBuilder.Create();
context.Items.Add("graph", request);
}
Run Code Online (Sandbox Code Playgroud)
然后通过注入 IHttpContextAccessor 来恢复它
public ClientesQueries(Microsoft.AspNetCore.Http.IHttpContextAccessor contextAccessor)
{
var queryRequest = contextAccessor.HttpContext.Items["graph"] as IReadOnlyQueryRequest;
}
Run Code Online (Sandbox Code Playgroud)
使用该代码,我可以创建一个表达式来查询数据库,仅查找客户端请求的数据。
有更好的方法来实现这一目标吗?
我不太确定我的答案是您所要求的,但这就是我在 graphql 请求中访问 httpContext 的方式。
只需添加 :[Service]IHttpContextAccessor httpContext作为方法的第一个参数。
我的代码中的完整示例:
public async Task<IEnumerable<Tenant>> GetTenants([Service]IHttpContextAccessor httpContext)
{
var tenantId = await httpContext.HttpContext.GetUserTenantId();
return await _metadataRepo.Tenants.Get(x => x.TenantId == tenantId);
}
Run Code Online (Sandbox Code Playgroud)
您不需要创建拦截器。HttpContext 已经在 HotChocolate 的 DI 中了。
祝你好运 !
| 归档时间: |
|
| 查看次数: |
3696 次 |
| 最近记录: |