在ASP.NET 应用集成 SignalR 浏览器聊天室示例和SignalR 浏览器聊天室示例代码分析中我们讲解了 ASP.NET 集成 SignalR 的具体步骤,现在对于更多的 .NET 站点使用的是ASP.NET MVC,今天就讲解下怎样在 ASP.NET MVC 中集成 SignalR。
如果你是使用VS2012,那么你可以按照下面的步骤操作:
下面的操作会教你使用 ASP.NET SignalR 2 和 ASP.NET MVC 5 搭建即时应用程序,使用在 ASP.NET 应用集成 SignalR 浏览器聊天室示例中同样的示例代码,只是我们创建的是一个 ASP.NET MVC5的应用。
我们主要需要做下面这几个操作:
下面的截图就是浏览器运行程序的样子,任何客户端访问页面,输入任何消息都会在其他客户端显示出来。

下面的步骤展示了怎样创建 ASP.NET MVC 5 应用、添加 SignalR 类库和创建聊天室应用。
打开 Visual Studio ,创建一个 C# ASP.NET 应用,.NET Framework 选择最新版,不得低于 4.5,然后命名为SignalRChat,点击确定。

选择 MVC,然后点击 Change Authentication

在 Change Authentication的对话框中选择 No Authentication,然后点击OK。

打开 Tools | Library Package Manager | Package Manager Console,运行下面的命令,添加一整套 SignalR 相关脚本文件和引用。
install-package Microsoft.AspNet.SignalR
在Solution Explorer中,展开 Scripts 节点,你可以看到 SignalR 相关 jQuery。

在项目种添加一个名叫Hubs的新文件夹。
在Solution Explorer中,右击“Project”,然后选择Add | SignalR Hub Class (v2)。将类命名为ChatHub.cs,并确定。你将使用这个类作为服务端的 hub 来发送消息到所有的客户端。

将ChatHub类的代码替换如下:
using System;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            // Call the addNewMessageToPage method to update clients.
            Clients.All.addNewMessageToPage(name, message);
        }
    }
}修改Startup类的代码如下:
using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}编辑 Controllers/HomeController.cs 下的 HomeController,添加下面的方法,这个方法会返回Chat的 View,接下类我们回来创建这个View。
public ActionResult Chat()
{
    return View();
}然后在 Views/Home 文件夹下添加一个名为Chat的View。

替换Chat.cshtml的内容如下所示:
@{
    ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<div class="container">
    <input type="text" id="message" />
    <input type="button" id="sendmessage" value="Send" />
    <input type="hidden" id="displayname" />
    <ul id="discussion">
    </ul>
</div>
@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.--> 
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.  
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page. 
                $('#discussion').append('<li><strong>' + htmlEncode(name) 
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.  
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub. 
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment. 
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}运行结果与前面讲解的ASP.NET 应用集成 SignalR 浏览器聊天室示例中效果是完全一致的,至于代码的分析可以参考上一篇教程SignalR 浏览器聊天室示例代码分析