如何创建作为订阅路由的GET路由



我有一个。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秒记录一个日期。

你可以这样做。

服务器代码:

[HttpGet]
public async Task Get(CancellationToken ct = default)
{
Response.StatusCode = 200;
Response.Headers["Content-Type"] = "application/x-ndjson";
// you can manage headers of the request only before this line
await Response.StartAsync(ct);

// cancellation token is important, or else your server will continue it's work after client has disconnected
while (!ct.IsCancellationRequested)
{
await Response.Body.WriteAsync(Encoding.UTF8.GetBytes("some data heren"), ct);
await Response.Body.FlushAsync(ct);
// change '5000' with whatever delay you need
await Task.Delay(5000, ct);
}
}

对应的客户端代码(c#示例):

var client = new HttpClient();
var response = await client.GetStreamAsync("http://localhost:5000/");
using var responseReader = new StreamReader(response);

while (!responseReader.EndOfStream)
{
Console.WriteLine(await responseReader.ReadLineAsync());
}

最新更新