2012-05-26 132 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 :( –