English 中文(简体)
HTML5 服务器侧边活动的 REST 网络服务
原标题:REST Webservice for HTML5 Server Side Events

目前我有一个 C# 控制台应用程序, 通过 < code> WebServicesHost 披露网站服务。 这些网站服务正被一个网站使用, 但现在我想在网站上添加 SSE 。

客户的代码是:

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

但在服务器方面, 当我试图定义合同时:

[OperationContract]
[WebGet]
String EventSource();

返回的服务是带字符串的 xml 。

在服务器方面,我应该做些什么来创建 SSE 可用的文件?

感谢您,谢谢您,谢谢您

最佳回答

如果您有操作合同, 返回类型总是以 XML 或可选性作为 JSON 序列。 如果您不想将返回值序列化, 则将返回类型定义为流 。

[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);

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

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签