Create A Chat web application using MVC Core and SignalR

SignalR is a .NET library that allows bi-direction communication between server and clients. The most popular applications using SignalR are probably chats. Here I'll show you how to create chat features using SignalR with MVC Core. It's a simple implementation to give you a clear view.

Here're the steps:

  1. Create a MVC Core application using Visual Studio Community 2017

    Choose File -> New -> Project -> ASP.NET Core Web Application- > Choose location -> Name it “SignalRTest” -> Select Model-View-Controller -> Click “OK” to create the project

  2. Install SignalR NuGet package

    Select Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution -> Click Browse tab -> Search “Microsoft.AspNet.SignalR.Core” -> Click “Install” -> Click OK -> Click “Accept”

  3. Modify Startup.cs in the project root folder

    1) Add the following line to the top of "ConfigureServices(IServiceCollection services)" method,

      services.AddSignalR();

    2) Change "Configure(IApplicationBuilder app, IHostingEnvironment env)" method, replace "app.UseMvc"section with the following code,

      app.UseMvc(routes =>
      {

        routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Chat}/{id?}");

      });

      app.UseSignalR(routes => {

        routes.MapHub ("/chat");

      });

      This replace the start page and register "/chat" action

    3) Add the following reference to the top of the file,

      using SignalRTest;

  4. Install the SignalR javascript client with NodeJS

    1) Open command line (Run As Administrator), change current directory to your solution root folder and run the following commands,

      npm init -y

      npm install @aspnet/signalr

    2) Copy "node_modules\@aspnet\signalr\dist\browser\signalr.js" file from generated "node_modules" folder to "wwwroot\js" folder

  5. Create a Chat.cs file in the project root folder inherit Hub class

      using Microsoft.AspNetCore.SignalR;
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Threading.Tasks;

      namespace SignalRTest
      {

        public class Chat : Hub
        {
          public Task Send( string message)
          {

            return Clients.All.SendAsync( "Send" , message);
          }
        }
      }

  6. Create Chat action in Home controller and add Chat View

    1) Create Chat method in HomeController.cs file

      public IActionResult Chat()
      {
        ViewData["Message"] = "Chat page." ;
        return View();
      }

    2) Right click "Chat()", select "Add View", use default options.

  7. Add following code to the bottom of Chat.cshtml file

      @section Scripts {

        <script src="~/js/signalr.js"></script>

        <script>
          let connection = new signalR.HubConnectionBuilder()
            .withUrl("/chat">)
            .configureLogging(signalR.LogLevel.Information)
            .build();

          connection.start();

          connection.on('send', (data) => {
            DisplayMessagesDiv = document.getElementById("DisplayMessages");
            DisplayMessagesDiv.innerHTML += "<li>" + data + "</li>";
          });

          function sendMessage()
          {
            var msg = document.getElementById("txtMessage").value;
            connection.invoke('send', msg);
          }
        </script>
      }

      <div class="container">
      <input type="text" id="txtMessage" />
      <input type="button" id="sendMessage" value="Send" onclick="sendMessage();" />
      <div id="DisplayMessages"></div>
      </div>


Now, it's time to run our Chat application. Please use Chrome or Edge as browser for debugging, since IE 11 doesn't support Javascript arrow functions.




Run the application in 2 browser windows, they can chat with each other like this,


Congraduations, everything is done!