【问题标题】:EventSource's response has a MIME type ("text/html") that is not "text/event-stream"EventSource 的响应具有不是“text/event-stream”的 MIME 类型(“text/html”)
【发布时间】:2012-10-31 19:39:20
【问题描述】:

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

EventSource 的响应有一个 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);
            }
        }
    }
}

有人可以帮我解决这个问题吗?万分感谢!

【问题讨论】:

    标签: c# javascript asp.net-mvc mime-types


    【解决方案1】:

    抱歉回复晚了。

    我在代码中所做的是在字符串构建器中准备我的整个响应,然后将其写入并立即刷新(不是 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 更多的数据。

    【讨论】:

      猜你喜欢
      • 2016-08-30
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      • 2018-06-14
      • 2018-03-30
      • 2019-08-06
      相关资源
      最近更新 更多