ApiController
后端API
public System.Net.Http.HttpResponseMessage GetUnknownNotices() { var user = FormsAuth.GetUserData(); var ns = new pl_NoticesService(); var nl = ns.GetNoticeList(user.UserID, false); return createHttpRequestMessage(Newtonsoft.Json.JsonConvert.SerializeObject(nl)); } System.Net.Http.HttpResponseMessage createHttpRequestMessage(string data) { var sb = new System.Text.StringBuilder(); sb.AppendFormat("retry:{0} ",10000); //推送间隔 sb.AppendFormat("event:{0} ", "message"); //绑定onmessage sb.AppendFormat("id:{0} ", DateTime.Now.Ticks.ToString()); sb.AppendFormat("data:{0} ", data); var response = new System.Net.Http.HttpResponseMessage { Content = new System.Net.Http.StringContent(sb.ToString(), System.Text.Encoding.GetEncoding("UTF-8"),"text/event-stream") }; response.StatusCode = System.Net.HttpStatusCode.OK; return response; }
前端JS
if (typeof (EventSource) != "undefined") { var es = new EventSource("/api/xxxx/GetUnknownNotices"); es.onmessage = function (event) { var data = JSON.parse(event.data); $('#msgCount').text(data.length+" ") }; es.onopen = function (event) { console.log("open:" + es.sta); }; es.onerror = function (event) { console.log("error:" + es.readyState); }; } else { console.log("该浏览器不支持"); }
参考: