With Azure Functions In-Process, streaming is not a problem. But the more modern Isolated mode seems to not work with streaming, or i am doing something wrong. This is what i tried:
[Function("HelloWorldStreaming")]
public async Task<HttpResponseData> RunHW([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, FunctionContext executionContext)
{
var logger = executionContext.GetLogger("HelloWorldFunction");
logger.LogInformation("C# HTTP trigger function processed a request.");
var response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", "text/event-stream; charset=utf-8");
response.Headers.Add("Cache-Control", "no-cache");
response.Headers.Add("Connection", "keep-alive");
response.Headers.Add("Transfer-Encoding", "chunked");
// Kick off the stream writing in a background task
_ = WriteToStreamAsync(response.Body, logger);
// Return the response immediately
return response;
}
private async Task WriteToStreamAsync(Stream responseStream, ILogger logger)
{
try
{
using (var writer = new StreamWriter(responseStream))
{
for (int i = 0; i < 10; i++)
{
await writer.WriteLineAsync($"data: Hello World {DateTime.Now}");
await writer.WriteLineAsync();
await writer.FlushAsync();
await Task.Delay(1000);
}
}
}
catch (Exception ex)
{
logger.LogError(ex, "Error occurred while writing to the stream.");
}
}
But only the first messsage gets streamed when not using the Transfer-Encoding header.
When using the Transfer-Encoding header, the Function Runtime exists with this error:
Executed ‘Functions.HelloWorldStreaming’ (Failed,
Id=6201ac98-a74c-4fd9-801d-b4c83f54b42a, Duration=347ms)
System.Private.CoreLib: Exception while executing function:
Functions.HelloWorldStreaming. Microsoft.Azure.WebJobs.Script.Grpc:
Failed to proxy request with ForwarderError: ResponseBodyDestination.
System.Net.Http: Received an invalid chunk extension:
’74-61-3A-20-48-65-6C-6C-6F-20-57-6F-72-6C-64-20-32-33-2E-30-35-2E-32-30-32-34-20-31-32-3A-31-34-3A-34-37′.
In In-Process mode, the function runtime stays alive until the stream has ended. What am i doing wrong?