1.要让Controller类的方法返回EventStream类型的数据,首先需要确保在 Startup.cs
或 Program.cs
文件中注册了 IHttpContextAccessor:
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// 添加服务到容器
builder.Services.AddHttpContextAccessor();
// 其他配置...
var app = builder.Build();
// 中间件配置...
app.Run();
}
}
2.在构造函数或方法注入拿到HttpContext
public class MyController : Controller
{
public Task TestEventStream([FromServices] IHttpContextAccessor httpContextAccessor,...Args args)
{
var httpContext = httpContextAccessor.HttpContext;
// 使用 httpContext
}
}
3.为上下文设置内容格式为event-stream
// 设置响应格式,设置缓存为关闭
httpContext.Response.ContentType = "text/event-stream";
httpContext.Response.Headers.Add("Cache-Control", "no-cache");
httpContext.Response.Headers.Add("Connection", "keep-alive");
4.使用StreamReader从流数据Stream中读取,并使用Response的Write方法写入Response的响应体当中
public async Task SetResponse(Stream stream,HttpContext context){
using StreamReader reader = new StreamReader(stream)
while(!reader.EndOfStream){
string? line = await reader.ReadLineAsync();
// 对line进行格式化处理
string? message = DealWithData(line);
// 写入到响应体当中
await context.Response.WriteAsync(message);
await httpContext.Response.Body.FlushAsync();
}
}