如果您有操作合同, 返回类型总是以 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 ;)