更新时间:2023-02-15 10:08:15
IHttpContextAccessor提供对上下文的访问并使用实现.感谢@ mj1313在此论坛中指出答案.,
IHttpContextAccessor provides access to context and use the implementation. Thanks to @mj1313 for pointing out the answer in this forum., Link
public class HomeController : Controller
{
private readonly IHttpContextAccessor _httpContextAccessor;
public HomeController(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public async Task<IActionResult> Contact()
{
..
var resp = _httpContextAccessor.HttpContext.Response;
resp.Headers.Add("Content-Type", "text/event-stream");
// Verify that the client is connected.
if (HttpContext.RequestAborted.IsCancellationRequested == false)
{
..
await resp.Body.WriteAsync(buffer, 0, length);
//or await resp.WriteAsync("hello");
resp.Body.Flush();
..
}
..
}
}