繁体   English   中英

EventSource的响应具有不是“ text / event-stream”的MIME类型(“ text / html”)

[英]EventSource's response has a MIME type (“text/html”) that is not “text/event-stream”

当我尝试将EventSource连接到我的控制器时,它一直在说:

EventSource的响应具有不是“ text / event-stream”的MIME类型(“ text / html”)。 中止连接。

我开设了以下课程来帮助您处理和准备响应。 我相信在这一节课中,我将responseType设置为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:250\n");
                    response.Write(string.Format("id:{0}\n", this.Version));
                    response.Write(string.Format("data:{0}\n\n", this.Content()));
                    response.End();
                }
                catch (HttpException e) { }
            }
            else
            {
                response.Write(String.Empty);
            }
        }
    }
}

有人可以帮我解决这个问题吗? 一千次提前致谢!

抱歉回复晚了。

我在我的代码确实是一个字符串生成器准备我的整个响应,然后把它写在刷新一次它(不是3结束写入)

var sb = new StringBuilder(); 
sb.Append("retry: 1\n");
sb.AppendFormat("id: {0}\n", this.Version);
sb.AppendFormat("id: {0}\n\n", this.Content());
Response.ContentType = "text/event-stream";
Response.Write(sb.ToString());
Response.Flush();

另外,我的代码在MVC控制器中,因此我不会自己创建响应(我使用this.Response),这意味着我的标头中可能包含的数据不仅仅是ContentType。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM