简体   繁体   English

在 graphql controller 响应上设置状态码

[英]setting status code on graphql controller response

guys I am sorry to post this question伙计们,我很抱歉发布这个问题

I am quite new to C# (having a javascript background) and I have been trying to set up an AsP.Net graphql server, I managed it, but the console of the server is always printing我对 C#(具有 javascript 背景)很陌生,我一直在尝试设置 AsP.Net graphql 服务器,我管理它,但服务器的控制台总是

 System.InvalidOperationException: StatusCode cannot be set because the response has already started.

my controller code is:我的 controller 代码是:


namespace server.Controllers
{

    [Route("graphql")]
    [ApiController]
    public class GraphqlController : ControllerBase
    {
        [HttpPost]
        public async Task<ActionResult> Post([FromBody] GraphQLQuery query)
        {
            var writer = new GraphQL.SystemTextJson.DocumentWriter();

            var schema = new MySchema();
            var inputs = query.Variables.ToInputs();
            var executer = new DocumentExecuter();
            var result = await executer.ExecuteAsync(_ =>
            {
                _.Schema = schema.GraphQLSchema;
                _.Query = query.Query;
                _.OperationName = query.OperationName;
                _.Inputs = inputs;
            });

            Response.ContentType = "application/json";
            Response.StatusCode = 200; // OK
            await writer.WriteAsync(Response.Body, result);
            if (result.Errors?.Count > 0)
            {
                return BadRequest();
            }
            else
            {
                return Ok(result);
            }
  
        }
    }
}

Can you help me with what am I doing wrong?你能帮我解决我做错了什么吗?

The reason is you already started the response, when using原因是您在使用时已经开始响应

        Response.ContentType = "application/json";
        Response.StatusCode = 200; // OK
        await writer.WriteAsync(Response.Body, result);

You are manually handling the response stream and what should be written to it.您正在手动处理响应 stream 以及应该写入的内容。

This actions is the same as what ASP.Net does when using Ok() .此操作与 ASP.Net 在使用Ok()时所做的相同。 ASP.Net write the result to the body of the response and setting the status code to 200. ASP.Net 将结果写入响应正文并将状态代码设置为 200。

Since you are handling the response by yourself your shouldn't really of using the functionality from ASP.Net.由于您自己处理响应,因此您不应该真正使用 ASP.Net 的功能。 You can just return a EmptyResult like below, and you should get the same response result without the error from the middleware.您可以只返回如下所示的EmptyResult ,并且您应该得到相同的响应结果,而不会出现来自中间件的错误。

return new EmptyResult();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM