简体   繁体   中英

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

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

my controller code is:


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.

This actions is the same as what ASP.Net does when using Ok() . ASP.Net write the result to the body of the response and setting the status code to 200.

Since you are handling the response by yourself your shouldn't really of using the functionality from ASP.Net. You can just return a EmptyResult like below, and you should get the same response result without the error from the middleware.

return new EmptyResult();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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