Using SignalR in an ASP.NET MVC Application

SignalR is a real-time communication framework from Microsoft. SignalR can be used for communications between the server and client and between clients by using the server as a go between. In this post, I will show you how to create yet another chat application (there are many already out there using SignalR) but I will look at some of the conventions and features in the framework to make it easier to integrate into your applications.Let’s get started by using NuGet to add a reference to the Microsoft.AspNet.SignalR library. This will install several different packages to your project including three other Microsoft.AspNet.SignalR libraries and there are a few dependencies on OWIN.

Next, add a new folder to your project. Name it Hubs. Having SignalR referenced in our project will allow us to create a new object type to our project named Hub. Right click the Hubs folder and hover over the Add menu item. In the resulting list, you should have an entry for SignalR Hub Class (v2). If you do, click it and name it ChatHub. If you don’t have the SignalR Hub Class (v2) option, just add a normal class named ChatHub. In the ChatHub class, copy the below code into it. You will have to change the namespace if you are copying the entire thing.

 

using Microsoft.AspNet.SignalR;

namespace AspNetMvcSignalRDemo.Hubs
{
    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            Clients.All.addMessage(name, message);
        }
    }
}

Let’s talk about this code listing for a second. I want to call your attention to the Send method name. The client-side proxy that gets generated for us will use pascal casing for send. It is important because it often trips up developers new to SignalR.

Now, in the page that you are using to test this, we need to add quite a bit of code and we need some structure in our HTML file. I am also assuming that you are using Bootstrap v3.

Lets start with the HTML. Paste the below code into your file.

<h2>Chat</h2>
<div class="container">
    <div class="row">
        <div class="col-md-6">
            <div class="form-horizontal">
                <div class="form-group">
                    <div class="col-md-6">
                        <input type="text" id="messageText" class="form-control" />
                    </div>
                    <div class="col-md-6">
                        <button type="button" id="sendMessage" class="btn btn-sm btn-success">Send</button>
                    </div>
                </div>
                <input type="hidden" id="displayName" />
            </div>
            <div style="margin-top: 20px;">
                <ul class="list-group" id="discussionList"></ul>
            </div>
        </div>
    </div>
</div>

Finally, we have to add piece of JavaScript to the page. I am using an external file but that is up to you.

$(function () {
    //This is a reference to the automatically generated proxy for the chatHub. Notice the casing.  
    var chatConnection = $.connection.chatHub;

    //We are adding a method to the chatConnection.client proxy so that it is available later.
    chatConnection.client.addMessage = function (name, message) {
        //Add the message to the page. 
        $('#discussionList').append('<li class="list-group-item"><strong>' + name
            + '</strong>: ' + message + '</li>');
    };

    //When the page loads, we will prompt the user to enter their name and then store that value in the 
    //hidden field so we can grab it later.
    $('#displayName').val(prompt('Enter your name:', ''));

    //Set initial focus to messageText input box.  
    $('#messageText').focus();

    //Start the connection.
    $.connection.hub.start().done(function () {
        $('#sendMessage').click(function () {
            //Call the Send method on the hub. Notice the casing of send. On the server, it is Send and on the client, send. 
            chatConnection.server.send($('#displayName').val(), $('#messageText').val());

            //Reset the textbox
            $('#messageText').val('').focus();
        });
    });
});

That is all there is to it. To test this, run the site and navigate to the page. I am using both Chrome and Edge at the same time to ensure it is working.

 

You can download a repo here.

Leave a Reply

Your email address will not be published.