如何为 .NET Core graphql 查询设置 AllowAnonymous
how to set AllowAnonymous for .NET Core graphql query
我在 .NET Core 3.1 中有这样的 graphql 查询:
public class CommentQuery : ObjectGraphType
{
public CommentQuery(CommentRepository commentRepository, UserInfo userInfo)
{
Field<ListGraphType<CommentType>>(
"contentComments",
arguments: new QueryArguments(new QueryArgument<StringGraphType> {Name = "contentItemId"}),
resolve: x =>
{
var contentItemId = x.GetArgument<string>("contentItemId");
return Task.Run(() =>
commentRepository.ListAsync(
Builders<Comment>.Filter.Where(p => p.ContentItemId == contentItemId))).Result;
});
Field<ListGraphType<CommentType>>(
name: "Comments",
arguments: new QueryArguments(new
QueryArgument<StringGraphType> { Name = "contentItemId" }),
resolve: x =>
{
var commentId = x.GetArgument<string>("commentId");
return Task.Run(() =>
commentRepository.ListAsync(
Builders<Comment>.Filter.Where(p => p.ContentItemId == commentId))).Result;
}
);
}
}
我需要在没有身份验证的情况下调用此查询。
默认情况下,我为 startup.cs
中的所有 api 启用身份验证
services.AddAuthentication(...)
经过搜索和尝试,我找到了解决方案:
在 Configure startup.cs 方法中添加一些行以允许这样的特定路径:
app.UseEndpoints(e =>
{
e.MapHealthChecks(BasePath + "/customers/comments/graphql", new HealthCheckOptions()
{
Predicate = (_) => false
})
.WithMetadata(new AllowAnonymousAttribute());
});
对我有用。
我在 .NET Core 3.1 中有这样的 graphql 查询:
public class CommentQuery : ObjectGraphType
{
public CommentQuery(CommentRepository commentRepository, UserInfo userInfo)
{
Field<ListGraphType<CommentType>>(
"contentComments",
arguments: new QueryArguments(new QueryArgument<StringGraphType> {Name = "contentItemId"}),
resolve: x =>
{
var contentItemId = x.GetArgument<string>("contentItemId");
return Task.Run(() =>
commentRepository.ListAsync(
Builders<Comment>.Filter.Where(p => p.ContentItemId == contentItemId))).Result;
});
Field<ListGraphType<CommentType>>(
name: "Comments",
arguments: new QueryArguments(new
QueryArgument<StringGraphType> { Name = "contentItemId" }),
resolve: x =>
{
var commentId = x.GetArgument<string>("commentId");
return Task.Run(() =>
commentRepository.ListAsync(
Builders<Comment>.Filter.Where(p => p.ContentItemId == commentId))).Result;
}
);
}
}
我需要在没有身份验证的情况下调用此查询。 默认情况下,我为 startup.cs
中的所有 api 启用身份验证services.AddAuthentication(...)
经过搜索和尝试,我找到了解决方案: 在 Configure startup.cs 方法中添加一些行以允许这样的特定路径:
app.UseEndpoints(e =>
{
e.MapHealthChecks(BasePath + "/customers/comments/graphql", new HealthCheckOptions()
{
Predicate = (_) => false
})
.WithMetadata(new AllowAnonymousAttribute());
});
对我有用。