0

我正在使用 GraphQL.Net 2.4.0 在 Asp.Net Core 2.2 中构建 GraphQL API

我创建了控制器来处理 GraphQL 查询:

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class GraphQLController : Controller
{
    private readonly ISchema _schema;
    private readonly IDocumentExecuter _executer;
    private readonly ILogger _logger;
    IEnumerable<IValidationRule> _validationRules;
    private readonly DataLoaderDocumentListener _dataLoaderDocumentListener;

    //private readonly IDocumentWriter _writer;
    //private readonly IHttpContextAccessor _accessor;

    public GraphQLController(
        ILogger<GraphQLController> logger,
        IEnumerable<IValidationRule> validationRules,
        IDocumentExecuter executer,
        DataLoaderDocumentListener dataLoaderDocumentListener,
        //IDocumentWriter writer,
        ISchema schema)
    {
        _executer = executer;
        _schema = schema;
        _logger = logger;
        _validationRules = validationRules;
        _dataLoaderDocumentListener = dataLoaderDocumentListener;
        //_writer = writer;
    }

    [Route("graphql")]
    [HttpPost]
    public async Task<IActionResult> PostAsync([FromBody]GraphQLQuery query)
    {

        if (!ModelState.IsValid || query == null)
        {
            return Json("Проблем в формата на изпратената на заявка!");
        }            

        var inputs = query.Variables.ToInputs();

        var result = await _executer.ExecuteAsync(o =>
        {
            o.Schema = _schema;
            o.Query = query.Query;
            o.OperationName = query.OperationName;
            o.Inputs = inputs;
            o.ExposeExceptions = true;
            o.EnableMetrics = true;

            o.ComplexityConfiguration = new GraphQL.Validation.Complexity.ComplexityConfiguration { MaxDepth = 15 };
            //o.FieldMiddleware.Use<InstrumentFieldsMiddleware>();
            o.UserContext = new GraphQLUserContext
            {
                // this is the User on your controller
                // which is populated from your jwt
                User = User

            };
            o.ValidationRules = DocumentValidator.CoreRules().Concat(_validationRules).ToList();
            o.Listeners.Add(_dataLoaderDocumentListener);

        }).ConfigureAwait(false);

        if (result.Errors?.Count > 0)
        {
            _logger.LogWarning($"Errors: {JsonConvert.SerializeObject(result.Errors)}");
            return BadRequest(result);
        }

        return Ok(result);
    }
}

当我想验证我的某些字段时出现问题InputObjectGraphType,我已经实现了IValidationRule接口。

在此之前,我将元数据添加到我要验证的字段中,以便我可以轻松找到它。我正在获取 fieldType 但无法获取值来验证它。

这是IValidationRulei 使用的实现:

    public class PhoneNumberValidationRule : IValidationRule
{
    public INodeVisitor Validate(ValidationContext context)
    {
        return new EnterLeaveListener(_ =>
        {
            _.Match<Argument>(argAst =>
            {
                var inputType = context.TypeInfo.GetInputType().GetNamedType() as InputObjectGraphType;
                var argDef = context.TypeInfo.GetArgument();
                if (argDef == null) return;

                var type = argDef.ResolvedType;
                if (type.IsInputType())
                {
                    var fields = ((type as NonNullGraphType)?.ResolvedType as IComplexGraphType)?.Fields;

                    if (fields != null)
                    {
                        foreach (var field in fields)
                        {
                            if (field.ResolvedType is NonNullGraphType)
                            {
                                if ((field.ResolvedType as NonNullGraphType).ResolvedType is IComplexGraphType)
                                {
                                    fields = fields.Union(((field.ResolvedType as NonNullGraphType).ResolvedType as IComplexGraphType)?.Fields);
                                }
                            }
                            if (field.ResolvedType is IComplexGraphType)
                            {
                                fields = fields.Union((field.ResolvedType as IComplexGraphType)?.Fields);
                            }
                        }

                        //let's look for fields that have a specific metadata
                        foreach (var fieldType in fields.Where(f => f.HasMetadata(nameof(EmailAddressValidationRule))))
                        {
                            //now it's time to get the value
                            context.Inputs.GetValue(argAst.Name, fieldType.Name);
                            if (value != null)
                            {
                                if (!value.IsValidPhoneNumber())
                                {
                                    context.ReportError(new ValidationError(context.OriginalQuery
                                    , "Invalid Phone Number"
                                    , "The supplied phone number is not valid."
                                    , argAst
                                    ));
                                }
                            }
                        }
                    }
                }
            });
        });
    }
}

但是这里的 context.Inputs 属性始终为空。在控制器中,这一行var inputs = query.Variables.ToInputs(); 也产生空值。此查询变量字段和文档执行器的输入字段与此有关吗?

4

1 回答 1

0

您现在可能已经想通了,但是对于将来发现这个问题的任何人:context.Inputs 仅与变量一起使用。据我了解,argAst.GetValue 可以是 VariableReference 也可以是 ObjectValue,具体取决于查询是否使用变量。如果未使用变量 context.Inputs.GetValue 将返回 null。

于 2019-11-10T09:13:42.960 回答