2012-05-26 89 views
0

目前,我有一个C#控制台应用程序通过WebServiceHost公开Web服务,但现在我试图将SSE添加到该站点。用于HTML5服务器端事件的REST Web服务

在客户端的代码是:

var source = new EventSource(server+'eventSource'); 
source.onmessage = function (event) { 
    alert(event.data); 
}; 

但在服务器端,当我尝试定义合同:

[OperationContract] 
[WebGet] 
String EventSource(); 

什么服务正在恢复服务是有一个xml串。

我应该怎样在服务器端创建一个可用于SSE的文档?

感谢advace

+0

请参阅:http://stackoverflow.com/questions/992533/wcf-responseformat-for-webget – seraphym

回答

2

如果你有一个OperationContract的,返回类型始终序列化为XML或optionaly为JSON。如果您不希望将返回值序列化,请将其定义为Stream。

[OperationContract] 
[WebGet] 
Stream EventSource(); 

// Implementation Example for returning an unserialized string. 
Stream EventSource() 
{ 
    // These 4 lines are optional but can spare you a lot of trouble ;) 
    OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; 
    context.Headers.Clear(); 
    context.Headers.Add("cache-control", "no-cache"); 
    context.ContentType = "text/event-stream"; // change to whatever content type you want to serve. 

    return new System.IO.MemoryStream(Encoding.ASCII.GetBytes("Some String you want to return without the WCF serializer interfering.")); 
} 

如果您自己构建流,请记得先执行.Seek(0, SeekOrigin.Begin);,然后再返回它。

编辑: 改变命令的顺序来设置ContentType后,头部得到清除。否则,你会清除刚刚设置的ContentType太;)

+0

谢谢,工作正常,我做的唯一更改是contentType for SSE是“事件流” –

+0

如果您直接从浏览器访问它工作正常,但是当它与SSE关联时,我会得到“EventSource的响应具有MIME类型(”application/octet-stream“),它不是”文字/事件流“”任何想法? –

+0

它设置为“文本/事件流”,我真的想要使用SSE :( –