Azure / Azure/azure-functions-host
Azure Function Proxy and Hybrid Connection for streaming
- Dominant language
- C#
- Stars
- 2k
- Forks
- 482
- Avg merge
- 2d 12h
- Merged PRs (30d)
- 38
Description
I have an asp.net core application running locally and I want to expose it on Internet. I'm using Azure Function Proxy and Hybrid Connection.
All things work great, except for an endpoint that streams data using WriteAsync in an infinite loop.
I reproduced the issue in a small app and I try to explain.
The Controller is below:
``` csharp
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace StreamingCoreSimulation.Controllers
{
[ApiController]
[Route("[controller]")]
public class StreamingController : ControllerBase
{
private Random _random = new Random();
private readonly ILogger _logger;
public StreamingController(ILogger logger)
{
_logger = logger;
}
[HttpGet("numbers")]
public Task Get()
{
HttpContext.Features.Get().DisableBuffering(); // with or without it's the same
return Task.FromResult(new PushStreamResult(WriteToStream, "application/json"));
}
[HttpGet("test")]
public IActionResult Test()
{
return Ok("All Fine!");
}
async void WriteToStream(Stream outputStream)
{
try
{
var exit = false;
while (true)
{
if (exit)
{
break;
}
var bytes = Encoding.UTF8.GetBytes(_random.Next().ToString());
using var memoryStream = new MemoryStream(bytes);
await memoryStream.CopyToAsync(outputStream);
await outputStream.WriteAsync(bytes, 0, bytes.Length);
byte[] newLine = Encoding.UTF8.GetBytes("\r\n");
await outputStream.WriteAsync(newLine, 0, newLine.Length);
await outputStream.FlushAsync(); // with or without it's the same
System.Threading.Thread.Sleep(1000);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
outputStream.Close();
}
}
}
}
```
The proxies.json is:
``` json
{
"$schema": "http://json.schemastore.org/proxies",
"proxies": {
"streaming": {
"matchCondition": {
"route": "/streaming/{*path}"
},
"backendUri": "http://localhost:44333/streaming/{path}"
}
}
}
```
Using Azure Function Proxy, when I call the *test* endpoint the response is right, when I call the *numbers* the response waits.
Putting a breakpoint in the *while* loop, the program is working.
If I force the *exit* flag to *true*, the loop stops and all generated numbers arrive immediately.
Running the same program locally, the data arrive during the *while* loop: this is what I would also with Azure Function Proxy.
My questions are:
- Is possible to use Azure Function Proxy to achieve this kind of goal?
- If the above answer is positive, what is the mistake that I'm doing?
Thank you!
Contributor guide
Assessment
This issue has not been assessed yet.