0

When I try to hook up the EventSource to my controller it keeps saying:

EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.

I made the following class to help with the handling and preparation of a response. In this class I believe I set the responseType accordingly to 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);
            }
        }
    }
}

Could someone please help me out on this one? Thousand times thanks in advance!

4

1 回答 1

0

Sorry for the late answer.

What I did in my code is prepare my whole response in a string builder and then write it and flush it at once (not 3 writes with an end)

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

on another note, my code is in an MVC controller, so I don't create the response myself (I use this.Response) meaning my header may contains more data than just the ContentType.

于 2013-02-15T07:41:31.350 回答