当我尝试将Eventsource连接到控制器时,它一直在说:
Eventsource的响应具有MIME类型(" text/html")不是 "文本/事件流"。中止连接。
我上了以下课程,以帮助处理和准备响应。在此课程中,我相信我将响应类型相应地设置为text/event-stream
。
public class ServerSentEventResult : ActionResult
{
public delegate string GetContent();
public GetContent Content { get; set; }
public int Version { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (this.Content != null)
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "text/event-stream"; response.BufferOutput = false; response.Charset = null;
string[] newStrings = context.HttpContext.Request.Headers.GetValues("Last-Event-ID");
if (newStrings == null || newStrings[0] != this.Version.ToString())
{
try
{
response.Write("retry:250n");
response.Write(string.Format("id:{0}n", this.Version));
response.Write(string.Format("data:{0}nn", this.Content()));
response.End();
}
catch (HttpException e) { }
}
else
{
response.Write(String.Empty);
}
}
}
}
有人可以帮我解决这个问题吗?提前感谢!
对不起。
我在代码中所做的是在字符串构建器中准备我的整个响应
var sb = new StringBuilder();
sb.Append("retry: 1n");
sb.AppendFormat("id: {0}n", this.Version);
sb.AppendFormat("id: {0}nn", this.Content());
Response.ContentType = "text/event-stream";
Response.Write(sb.ToString());
Response.Flush();
在另一个注意事项上,我的代码位于MVC控制器中,因此我不会自己创建响应(我使用this.response),这意味着我的标题可能包含的数据可能不仅仅是contentType。