簡體   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