我正在尝试为网页实现简单的推送通知机制。因此,我使用以下方法创建了WebAPI控制器:
[HttpGet]
public HttpResponseMessage Subscribe()
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new PushStreamContent(
(stream, headers, context) => OnStreamAvailable(stream, headers, context),
"text/event-stream"
);
return response;
}
但是当我尝试从客户端代码中调用它时:
function listen() {
if (!!window.EventSource) {
const server = new EventSource('http://localhost:5000/api/Notifications/');
server.addEventListener('message', function (e) {
const json = JSON.parse(e.data);
console.log('message', json);
});
server.addEventListener('open', function (e) {
console.log('open');
});
server.addEventListener('error', function (e) {
if (e.readyState === EventSource.CLOSED) {
console.log('error');
}
});
}
}
Chrome回复了我一个EventSource's response has a MIME type ("application/json") that is not "text/event-stream". Aborting the connection.
我必须补充一点,我正在编写的代码基于this教程(使用MVC5)。
我的问题是:如何使Subscribe
方法有效?预先感谢。