可能会向使用GraphQL.NET和asp.net core 2实现的Graphql服务器发送空请求。
我尝试使用asp.net core 2动作过滤器来实现它,但似乎无法正常工作。
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc(options =>
{
options.Filters.Add(typeof (CheckModelForNullAttribute));
options.Filters.Add(typeof (ValidateModelStateAttribute));
}
).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// GraphQLController.cs
[Route("[controller]")]
public class GraphQLController : Controller
{
private readonly IDocumentExecuter _documentExecuter;
private readonly ISchema _schema;
public GraphQLController(ISchema schema, IDocumentExecuter documentExecuter)
{
_schema = schema;
_documentExecuter = documentExecuter;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] GraphQLQuery query)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
var inputs = query.Variables.ToInputs();
var executionOptions = new ExecutionOptions{Schema = _schema, Query = query.Query, Inputs = inputs, UserContext = Request.Headers, //UserContext = new GraphQLUserContext { Headers = Request.Headers }
};
var result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false);
if (result.Errors?.Count > 0)
{
return BadRequest(result);
}
return Ok(result);
}
}
// CheckModelForNullAttribute.cs
public class CheckModelForNullAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (context.ActionArguments.Any(c => c.Value == null))
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
}
// ValidateModelStateAttribute.cs
public class ValidateModelStateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
}
有人可以帮助我解决此问题吗?