0

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);
            }
        }
    }
}

誰かがこれについて私を助けてくれませんか?何千回もよろしくお願いします!

4

1 に答える 1

0

返事遅れてすみません。

私がコードで行ったことは、文字列ビルダーで応答全体を準備し、それを書き込んで一度にフラッシュすることです (最後に 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 以外のデータが含まれる場合があります。

于 2013-02-15T07:41:31.350 に答える