问题
I am using Server Sent Events in ServiceStack and I need to allow its use across origins.
I have setup the ServiceStack CorsFeature
in my application, but this is not honoured by the ServerEventsFeature
.
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","*");
}
...
}
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?
Thanks.
回答1:
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.
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.
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(...);
},
...
}
This change is available from v4.0.34+ that's now available on MyGet.
来源:https://stackoverflow.com/questions/26741158/server-sent-events-with-cors-support