Home > other >  Azure Functions: StatusCode cannot be set because the response has already started
Azure Functions: StatusCode cannot be set because the response has already started

Time:05-09

I am trying to stream data from my Azure Function and all is fine but I get an error after it has executed.

This is the code:

[FunctionName("QueryData")]
public async Task QuerySingleMessages([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req)
{
     var message = await req.GetPostMessage<Message>();
     
     var response = req.HttpContext.Response; 
     response.StatusCode = 200;
     response.ContentType = "application/json-data-stream";
            
     var sw = new StreamWriter(response.Body);
     
     foreach (var msg in this.messageReaderService.FindLatestMessages(message.keys))
     {
         var json = System.Text.Json.JsonSerializer.Serialize(
                    msg,
                    new JsonSerializerOptions {PropertyNameCaseInsensitive = false});
         await sw.WriteAsync(json);
     }

     await sw.FlushAsync();
     await sw.DisposeAsync();
}

this is the error:

[2022-05-06T15:15:17.034Z] Executed 'QueryData' (Succeeded, Id=df70d5a7-37d7-40ef-b446-ecceb943e454, Duration=1350ms)
[2022-05-06T15:15:17.047Z] An unhandled host error has occurred.
[2022-05-06T15:15:17.048Z] Microsoft.AspNetCore.Server.Kestrel.Core: StatusCode cannot be set because the response has already started.

Is there a configuration (or something else) I can change so that I can stop the host error to occur?

Thanks

CodePudding user response:

After reproducing from our end we could able to get this work when we tried fixing the return type and return the EmptyResult i.e., return new EmptyResult();.

[FunctionName("Function1")]
        public static async Task<EmptyResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var message = await req.GetPostMessage<Message>();

            var response = req.HttpContext.Response;
            response.StatusCode = 200;
            response.ContentType = "application/json-data-stream";

            var sw = new StreamWriter(response.Body);

            foreach (var msg in this.messageReaderService.FindLatestMessages(message.keys))
            {
                var json = System.Text.Json.JsonSerializer.Serialize(
                           msg,
                           new JsonSerializerOptions { PropertyNameCaseInsensitive = false });
                await sw.WriteAsync(json);
            }

            await sw.FlushAsync();
            await sw.DisposeAsync();

            return new EmptyResult();
        }
  • Related