如果您有 OperationContract,则返回类型始终序列化为 XML 或可选的 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 ;)