Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# HTML5服务器端事件的REST Web服务_C#_Web Services_Html_Rest - Fatal编程技术网

C# HTML5服务器端事件的REST Web服务

C# HTML5服务器端事件的REST Web服务,c#,web-services,html,rest,C#,Web Services,Html,Rest,目前,我有一个C#console应用程序,它通过WebServiceHost公开Web服务,这些Web服务正被一个网站使用,但现在我正在尝试将SSE添加到该网站 客户端的代码是: var source = new EventSource(server+'eventSource'); source.onmessage = function (event) { alert(event.data); }; 但在服务器端,当我尝试定义契约时: [OperationContract] [WebG

目前,我有一个C#console应用程序,它通过
WebServiceHost
公开Web服务,这些Web服务正被一个网站使用,但现在我正在尝试将SSE添加到该网站

客户端的代码是:

var source = new EventSource(server+'eventSource');
source.onmessage = function (event) {
  alert(event.data);
};  
但在服务器端,当我尝试定义契约时:

[OperationContract]
[WebGet]
String EventSource();
服务返回的是一个带有字符串的xml

我应该在服务器端做什么来创建一个可供SSE使用的文档


感谢advace

如果您有OperationContract,返回类型总是序列化为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)返回之前

编辑:
更改了命令顺序,以便在清除标头后设置ContentType。否则您也会清除新设置的ContentType;)

请参阅:谢谢,工作正常,我所做的唯一更改是SSE的contentType,它是“事件流”,如果您直接从浏览器访问,它工作正常,但是当它与SSE关联时,我得到“EventSource的响应具有MIME类型(“应用程序/八位字节流”),它不是“文本/事件流”。有什么想法吗?它被设置为“文本/事件流”我真的很想使用SSE:(我已经用简单的rest客户端检查过了,我得到了“内容类型:应用程序/八位字节流”:S我如何更改它?我不小心在示例代码中键入了错误的顺序。请在标题后面加上带有
context.ContentType=“…”;
声明。我相应地更改了答案中的代码。如果您设置了内容类型,然后清除所有无法工作的内容;)