Server Sent Events + Asp Core,为什么我不能让它工作?

Server Sent Events + Asp Core, why I can't make it work?

我尝试 SSE 只是为了看看它们是如何工作的,但我不明白为什么这段代码不起作用。我收到客户端错误。 在我的 asp 控制器中:

public class Example {
    public Example() {
        X = "12";
        Y = 5;
    }

    public string X { get; set; }
    public int Y { get; set; }
}

public IActionResult Index() {
    return View();
}

public async Task Messaggio() {
    Response.Headers.Add("Content-Type", "text/event-stream");
    var msg = System.Text.Json.JsonSerializer.Serialize(new Example());
    var bytes = Encoding.ASCII.GetBytes(msg);
    await Response.Body.WriteAsync(bytes, 0, bytes.Length);
    await Response.Body.FlushAsync();
    Response.Body.Close();
}

客户端生成 html:

<html><head>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
</head>
<body>

ciaoooo
<div id="Messaggio"></div>

<script>
    source = new EventSource('/Home/Messaggio');
    source.onopen = function (ddd) {
        console.log("aperta");
    };
    source.onerror = function (ddd) {
        console.log("errore");
        console.log(ddd.data);
        source.close();
    };

    source.onmessage = function (ddd) {
        $("#Messaggio").text(ddd.data);
        console.log(ddd.data);
    };
</script>

</body>
</html>

浏览器控制台输出:

aperta
errore
undefined

路由没问题,因为如果我请求 /home/messaggio 它确实有效,我会得到 Json 文件

感谢任何能帮助我的人。

你在返回的"msg"之前没有添加"data"属性,所以在js中无法获取到ddd.data

修改Messaggio动作如下:

 public async Task Messaggio()
    { 
        Response.Headers.Add("Content-Type", "text/event-stream");
        var msg = System.Text.Json.JsonSerializer.Serialize(new Example());
        var bytes = Encoding.ASCII.GetBytes($"data: {msg}\n\n");
        await Response.Body.WriteAsync(bytes, 0, bytes.Length);
        await HttpContext.Response.Body.FlushAsync();
        Response.Body.Close(); 
    }

结果如下: