ApiController
バックエンドAPI
公共System.Net.Http.HttpResponseMessageのGetUnknownNotices() { VARユーザ= FormsAuth.GetUserData()。 VaRの NS = 新しいpl_NoticesService(); VAR NL = ns.GetNoticeList(user.UserID、偽); 返すcreateHttpRequestMessage(Newtonsoft.Json.JsonConvert.SerializeObject(NL)); } System.Net.Http.HttpResponseMessage createHttpRequestMessage(文字列データ) { VARの SB = 新しいSystem.Text.StringBuilder()。 sb.AppendFormat(" リトライ:{0} \ n "、10000); // 推送间隔 sb.AppendFormat(" イベント:{0} \ n "、" メッセージ")。// 绑定のonMessage sb.AppendFormat(" ID:{0} \ n " 、DateTime.Now.Ticks.ToString())。 sb.AppendFormat(" データ:{0}の\ n " 、データ)。 VaRの応答= 新しいSystem.Net.Http.HttpResponseMessage { コンテンツ = 新しい System.Net.Http.StringContent(sb.ToString()、System.Text.Encoding.GetEncoding("UTF-8 ")、" テキスト/イベント・ストリーム」) }; response.StatusCode = System.Net.HttpStatusCode.OK; 返す応答を; }
JSフロントエンド
もし(typeof演算!(のEventSource)= "未定義" ){ VAR ES = 新しいのEventSource( "/ API / XXXX / GetUnknownNotices" ); es.onmessage = 関数(イベント){ VARのデータ= JSON.parse(event.data)。 $( '#msgCount')テキスト(data.length + "\ N \ N" ) }; es.onopen = 関数(イベント){ にconsole.log( "オープン" + es.sta)。 }。 es.onerror = 関数(イベント){ にconsole.log( "エラー:" +es.readyState); }; } そうでなければ{ にconsole.log( "ブラウザがサポートしていません" ); }
参考: