0

At the moment I have an C# console application that exposes Web Services through WebServiceHost those web services are being used by an website but now I'm trying to add SSE to the site.

The code at the client is:

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

But on the server side, when I try to define the contract:

[OperationContract]
[WebGet]
String EventSource();

What the service is returning service is a xml with a String.

What should I do on the server side to create a document available for SSE?

Thanks in advace

Filburt
  • 17,626
  • 12
  • 64
  • 115
Mario Corchero
  • 5,257
  • 5
  • 33
  • 59

1 Answers1

2

If you have an OperationContract, the return Type is always serialized as XML or optionaly as JSON. If you do not want the return value to be serialized define it as 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.")); 
}

If you build the stream yourself remember to exectute .Seek(0, SeekOrigin.Begin); before you return it.

EDIT: Changed the command order to set the ContentType AFTER the Header gets cleard. Otherwise you would clear the freshly set ContentType too ;)

Gerald Degeneve
  • 547
  • 2
  • 8
  • thanks, works fine, the only change i did was the contentType for the SSE wich is "event-stream" – Mario Corchero May 26 '12 at 15:27
  • If you access directly from the browser it works fine but when it is associated to a SSE I get "EventSource's response has a MIME type ("application/octet-stream") that is not "text/event-stream"" any ideas? – Mario Corchero May 26 '12 at 17:53
  • it is set as "text/event-stream" and I really want to use SSE :( – Mario Corchero May 26 '12 at 21:18
  • I have checked it with the simple rest client and I got "Content-Type: application/octet-stream" :S how can I change it? – Mario Corchero May 26 '12 at 21:26
  • 1
    I accidently typed the wrong order in the sample code. Please put the line with `context.ContentType = "...";` AFTER the Headers.Clear() statement. I changed the code in my answer acordingly. If you set the content type and aftewards clear everything it cannot work ;) – Gerald Degeneve May 26 '12 at 23:44