开发者

How to implement Server Sent Events in MVC3 using .NET?

I want to make a feed application using SSE in MVC .NET. I was开发者_C百科 looking over the web but I can't find an example or a way to implement the SSE in MVC. I developed a very dirty solution where a View calls a Controller that calls a second View, and this 2nd View makes the push to the first one. I hope that somebody can help. Thanks.


Take a look at SignalR. It is very easy to set up and get running, and there are plenty of examples in ASP.NET to get you started.


If ASP.NET WebApi is an option you can checkout my library, ServerSentEvents4Net. The code is up on Github, and its also available on Nuget.


Here's an example to implement sse in mvc4 using .net (it should work fine for MVC3 also) Controller part:

 public ActionResult Index()
        {
            ViewBag.Message = "SSE WITH ASP.NET MVC";
            return View();
        }
        public ActionResult Message()
        {
            var result = string.Empty;
            var sb = new StringBuilder();
            sb.AppendFormat("data: {0}\n\n", DateTime.Now.ToString());
            return Content(sb.ToString(), "text/event-stream");

        }

View Part:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script type="text/javascript">

            function contentLoaded() {
                var source = new EventSource('home/message');
                //var ul = $("#messages");
                source.onmessage = function (e) {

                    var li = document.createElement("li");
                    var returnedItem = e.data;
                    li.textContent = returnedItem;
                    $("#messages").append(li);
                }
            };

            window.addEventListener("DOMContentLoaded", contentLoaded, false);
        </script>
        <h2><%: ViewBag.Message%></h2>
        <p>
            SSE WITH ASP.NET MVC
        </p>
        <ul id="messages">
        </ul>

Output:

How to implement Server Sent Events in MVC3 using .NET?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜