具有CORS支持的服务器发送事件 [英] Server Sent Events with CORS support
问题描述
我正在使用 ServiceStack中的服务器发送事件,我需要允许它跨源使用.
I am using Server Sent Events in ServiceStack and I need to allow its use across origins.
我已经在我的应用程序中设置了ServiceStack CorsFeature
,但是 ServerEventsFeature
并没有实现这一点.
I have setup the ServiceStack CorsFeature
in my application, but this is not honoured by the ServerEventsFeature
.
我可以在 OnCreated
中手动添加 Access-Control-Allow-Origin
标头,并允许请求对 event-stream
进行请求,但是对心跳的请求失败,因为我无法对此请求设置标头.
I can manually add the Access-Control-Allow-Origin
header in the OnCreated
, and that allows requests to event-stream
, but requests to the heartbeat fail, because I cannot set a header on this request.
Plugins.Add(new ServerEventsFeature {
HeartbeatInterval = new TimeSpan(0,0,30),
OnCreated = (subscription, request) => {
request.Response.AddHeader("Access-Control-Allow-Origin","*");
}
...
}
由于SSE功能在RawHandler上实现了,我看不到如何将此标头添加到请求中.有没有一种方法可以为所有/event-
网址设置标头?
As the SSE functionality is implemented on a RawHandler, I can't see how to get this header into the request. Is there a way I can set the header for all /event-
url's?
谢谢.
推荐答案
只有/event-stream
和/event-heartbeat
是原始HTTP处理程序,其他 event-*
路由是通过ServiceStack的请求管道的常规ServiceStack服务.
Only the /event-stream
and /event-heartbeat
are Raw HTTP Handlers, the other event-*
routes are normal ServiceStack services which go through ServiceStack's Request Pipeline.
我添加了一个更改,以自动将 Config.GlobalResponseHeaders
应用于/event-stream
和/event-heartbeat
处理程序 .现在,此更改应在启用CorsFeature时自动添加 CORS标头.
I've added a change to automatically apply Config.GlobalResponseHeaders
to both /event-stream
and /event-heartbeat
handlers in this commit. This change should now automatically add the CORS Headers when CorsFeature is enabled.
我还为/event-heartbeat
回调添加了 OnHeartbeatInit
,以匹配/event-stream
OnInit
回调,因此您还可以向心跳处理程序中添加自定义标头.
I've also added OnHeartbeatInit
for /event-heartbeat
callback to match /event-stream
OnInit
callback so you can also add custom headers to the Heartbeat handler as well.
Plugins.Add(new ServerEventsFeature {
HeartbeatInterval = new TimeSpan(0,0,30),
OnInit = (request) => {
request.Response.AddHeader(...);
},
OnHeartbeatInit = (request) => {
request.Response.AddHeader(...);
},
...
}
此更改可从 v4.0.34 + 版本开始,该版本现在MyGet .
This change is available from v4.0.34+ that's now available on MyGet.
这篇关于具有CORS支持的服务器发送事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!