Server Sent Events with CORS support

≡放荡痞女 提交于 2019-12-13 18:28:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!