【问题标题】:How to create a GET route acting as a subscription route如何创建充当订阅路由的 GET 路由
【发布时间】: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


【解决方案1】:

你可以这样完成。

服务器代码:

[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 here\n"), 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());
}

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2015-05-15
    • 1970-01-01
    • 2016-03-01
    • 2023-03-31
    • 2018-04-28
    相关资源
    最近更新 更多