【发布时间】:2021-11-07 18:02:21
【问题描述】:
我有一个 .Net 5 Web API 并想创建一个 GET 端点(充当订阅)每 x 秒发送一次数据。我知道那里有工具,例如SignalR,但我想知道是否可以通过简单的路线达到相同的结果。也许流可以帮助...
这是我的示例控制器
[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase
{
[HttpGet]
public OkResult SendDataEvery5Seconds()
{
return Ok(); // send back an initial response
// send data every 5 seconds
}
}
我不知道 C# 是否可以做到这一点,但我尝试使用 Node 创建一个工作示例,展示我想要实现的目标:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.writeHead(200, {
'content-type': 'application/x-ndjson'
});
setInterval(() => {
res.write(JSON.stringify(new Date()) + '\n');
}, 5000);
})
app.listen(3000);
运行 curl -i http://localhost:3000 应该每 5 秒写下一个日期。
【问题讨论】:
-
您的控制器有一个
Response属性,您可以在其中手动发送响应数据。 (Response.Body)。 -
尝试使用 thread.sleep 编写 while 循环并将数据写入响应。
while (true) { Thread.Sleep(5000); return Ok();} -
这将耗尽您的服务器,因为即使客户端关闭,该方法也会继续运行。
标签: c# asp.net-web-api .net-core asp.net-core-webapi .net-5