Saturday, April 6, 2013

Tutorial: Simple SignalR Hub with ASP.NET MVC 4

ASP.NET SignalR is a new HTTP technology that allows for a persistent connection between a client and a server. Check out for more information on SignalR.

Here is a tutorial on creating a simple “Chat” SignalR server application using C# and ASP.NET MVC 4 in Visual Studio 2012. The client application will be an ASP.NET MVC View.

  1. Start Visual Studio 2012.
  2. File >> New Project… >> Visual C# >> Web >> ASP.NET MVC 4 Web Application. Name the application “MvcChatSignalR” then click on OK.
  3. Select the Empty template and the Razor view engine. For this example, there is no need to create a unit test project. Click on the OK button.
  4. In the NuGet “Package Manager Console”, type: Install-Package Microsoft.AspNet.SignalR. This will install all the bits necessary for SignalR.
  5. The “readme.txt” file pops up in Visual Studio. You are reminded that the “RouteTable.Routes.MapHubs();” code must be placed inside your Global.asax.cs file. Copy this code and paste it into the “Global.asax.cs” file right after “AreaRegistration.RegisterAllAreas();” as shown below:
    protected void Application_Start() {

    The SignalR route must be placed before the MVC route so that the requests for the hub are not swallowed up by the MVC route.

  6. Next, we will create a server-side hub. Create a folder named “Hubs” and in there create a class named “Chat.cs”. The Chat class inherits from the “Hub” base type and implements the server-side logic. Any public method declared in the hub class is callable from SignalR clients. Make sure the “Chat.cs” class file looks like this:
    public class Chat : Hub { 
    public void SendMessage(string nick, string message) {
    Clients.All.PublishMessage(nick, message);
    “PublishMessage” is not defined on the server-side application. This is a dynamic function that will be called in the client’s JavaScript. You can, if you like, annotate the server hub class with another name that the client can use. For example, we can give the server class the name “MessageSender” with annotation [HubName(“MessageSender ”)]. We are not doing this in our simple example.

  7. Since we created an empty MVC 4 project, we do not have a _Layout.cshtml page. Create a folder named “Shared” under Views. Inside the “Shared” folder, add a file named “_Layout.cshtml” with the following content:
    <!DOCTYPE html>
    <html lang="en">
    <meta charset="utf-8" />
    <title>@ViewBag.Title - My SignalR Chat Hub</title>
    <link href="~/favicon.ico" rel="shortcut icon"
    type="image/x-icon" />
    <link href="~/Content/Site.css" rel="stylesheet" />
    <meta name="viewport" content="width=device-width" />
    <div id="body">
    <section class="content-wrapper main-content clear-fix">

  8. In the “Controllers” folder, add a new controller named “HomeController” using the “Empty MVC controller” template as shown below:
  9. To create a view for the Index action method, right-click on “Index()” and select “Add View…”. This opens up the “Add View” dialog. y1giyb3b
  10. Simply click on the “Add” button without changing anything. This creates a plain file “Index.cshtml” in the in the Views/Home folder.
  11. Replace the code in “Index.cshtml” with the following code:
    <label for="nick" >Your chat nickname:</label><br />
    <input type="text" name="nick" id="nick" />
    <br /><br />
    <label for="message" >Message:</label><br />
    <input type="text" name="message" id="message" maxlength="100" />
    <div id="chatWindow" style="width: 100%; height: 300px; overflow: scroll; border: 1px solid grey"></div>
    <br />
    <script src="~/Scripts/jquery-1.6.4.min.js"></script>
    <script src="~/Scripts/jquery.signalR-1.0.1.min.js"></script>
    <script type="text/javascript" src="/signalr/hubs"></script>
    $(function () {
    // get handle to chat hub generated by SignalR
    var chatHub = $;

    // add method that can be called by the hub to update chat
    chatHub.client.publishMessage = function (nick, msg) {
    var chatWin = $("#chatWindow");
    chatWin.html(chatWin.html() + "<b>" + nick + "</b>: " + msg + "<br />");

    // start the connection with the hub
    $(document).keypress(function (e) {
    if (e.which == 13) {
    // when the 'Enter' key is pressed, send the message to hub
    chatHub.server.sendMessage($("#nick").val(), $("#message").val());

  12. Make sure you adjust the names of the JavaScript files to suit your environment. Also, note that the JavaScript file “/signalr/hubs” is not a physical file on the server. It is dynamically generated by the server
  13. Compile and run the application. Open two different browsers (for example Chrome and IE) that point to the same URL. As you post a message from one browser, it shows up in both browsers. This is the power of SignalRdm2f3ch1

I hope you found this short tutorial useful. At this point, I am sure your mind is spinning with potential applications that you can build with this technology.