ASP.NET MVC Chat Application Using SignalR

Introduction

SignalR is a web-based real-time bidirectional communication framework. It’s very useful in terms of user-friendliness. While developing a chat application or broadcasting the message like notification popup, before SignalR came into the picture, we used to use the request/response technology where the server had to wait for the client’s request. On the other hand, in SignalR, we can directly push the message to the clients.

It has three important transport mediums as mentioned below.

  1. Server-Sent Event.
  2. ForEver Frame.
  3. Long Polling.

Implementation

Step 1

Open Visual Studio and create a new ASP.NET web application.

Step 2

Select MVC and authentication mode as “No Authentication”.

Step 3

Open Package Manager Console and type the following command to install the NuGet package. Alternatively, click Add >> New Item >> SingalR and the select SignalR Hub Class (v2) followed by a click on the OK button.

install-package Microsoft.AspNet.SignalR

ASP.NET MVC Chat Application By Using SignalR
 
ASP.NET MVC Chat Application By Using SignalR
 
ASP.NET MVC Chat Application By Using SignalR

Step 4

In Myhub1.cs class, add the following method.

  1. public void Send(string name, string message)  
  2.   {              
  3.       Clients.All.addNewMessageToPage(name, message);  
  4.   }   

Step 5

In Solution Explorer, right click and add a new class with the name as “Startup.cs” and then, install “Microsoft.Owin” NuGet package.

Step 6

Open the HomeController.cs class and add the chat method.

Step 7

Create a new View called “Chat” under "Home" folder and delete the existing code from View and add the below code.
  1. @{  
  2.     ViewBag.Title = "Chat";  
  3. }  
  4. <h2>Chat</h2>  
  5. <script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>  
  6. <div class="container">  
  7.     <input type="text" id="message" />  
  8.     <input type="button" id="sendmessage" value="Send" />  
  9.     <input type="hidden" id="displayname" />  
  10.     <ul id="discussion"></ul>  
  11. </div>  
  12. @section scripts {  
  13.     <!--Script references. -->  
  14.     <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->  
  15.     <!--Reference the SignalR library. -->  
  16.     <script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>  
  17.     <!--Reference the autogenerated SignalR hub script. -->  
  18.     <script src="~/signalr/hubs"></script>  
  19.     <!--SignalR script to update the chat page and send messages.-->  
  20.     <script>  
  21.         $(function () {  
  22.             // Reference the auto-generated proxy for the hub.  
  23.             var chat = $.connection.myHub1;  
  24.             // Create a function that the hub can call back to display messages.  
  25.             chat.client.addNewMessageToPage = function (name, message) {  
  26.                 // Add the message to the page.  
  27.                 $('#discussion').append('<li><strong>' + htmlEncode(name)  
  28.                     + '</strong>: ' + htmlEncode(message) + '</li>');  
  29.             };  
  30.             // Get the user name and store it to prepend to messages.  
  31.             $('#displayname').val(prompt('Enter your name:'''));  
  32.             // Set initial focus to message input box.  
  33.             $('#message').focus();  
  34.             // Start the connection.  
  35.             $.connection.hub.start().done(function () {  
  36.                 $('#sendmessage').click(function () {  
  37.                     // Call the Send method on the hub.  
  38.                     chat.server.send($('#displayname').val(), $('#message').val());  
  39.                     // Clear text box and reset focus for next comment.  
  40.                     $('#message').val('').focus();  
  41.                 });  
  42.             });  
  43.         });  
  44.         // This optional function html-encodes messages for display in the page.  
  45.         function htmlEncode(value) {  
  46.             var encodedValue = $('<div />').text(value).html();  
  47.             return encodedValue;  
  48.         }  
  49.     </script>  
  50. }   

Step 8

Create a chat menu in the _Layout.cshtml file as shown below.

  1. <li>@Html.ActionLink("Home""Chat""Chat")</li>   
ASP.NET MVC Chat Application By Using SignalR
 
ASP.NET MVC Chat Application By Using SignalR
 

Conclusion

Save all the files in Visual Studio and run the same. In the browser, the system will ask us to enter the name. Copy the http://localhost:62167/Home/Chat URL and put it into another browser tab.

That’s all. Now, we can enjoy the chat.

Code Sample

Startup.cs

  1. using Microsoft.Owin;  
  2. using Owin;  
  3.   
  4. [assembly: OwinStartup(typeof(SignalRChat.Startup))]  
  5. namespace SignalRChat  
  6. {  
  7.     public class Startup  
  8.     {  
  9.         public void Configuration(IAppBuilder app)  
  10.         {  
  11.             // Any connection or hub wire up and configuration should go here  
  12.             app.MapSignalR();  
  13.         }  
  14.     }  
  15. }  

ChatHub.cs

  1. public class ChatHub : Hub  
  2.     {  
  3.         public void Send(string name, string message)  
  4.         {  
  5.             // Call the addNewMessageToPage method to update clients.  
  6.             Clients.All.addNewMessageToPage(name, message);  
  7.         }  
  8.     }  

Global.asax.cs

  1. public class MvcApplication : System.Web.HttpApplication  
  2.     {  
  3.         protected void Application_Start()  
  4.         {  
  5.             AreaRegistration.RegisterAllAreas();  
  6.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  7.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
  8.             BundleConfig.RegisterBundles(BundleTable.Bundles);  
  9.         }  
  10.     }  


Similar Articles