Click here to Skip to main content
15,306,676 members
Articles / Programming Languages / C#
Posted 20 Dec 2017


67 bookmarked

SignalR Chat App with ASP.NET WebForm And BootStrap - Part One

Rate me:
Please Sign up or sign in to vote.
5.00/5 (35 votes)
20 Dec 2017CPOL6 min read
Integration of SignalR with ASP.NET C# WebForm Application in Real-Time Chat Application
In this article, we are going to learn to create a real-time chat application using SignalR, Bootstrap, and jQuery Modal Popup.


In this article, I am going to share with you how to integrate and use SignalR with ASP.NET WebForm Application.

Here, we are going to learn to create a real-time chat application using SignalR, Bootstrap, and jQuery Modal Popup. There is a Login system for existing users and registration for new users. First, the user has to create an account and then they can login by using their login credentials, so the login authentications are required. After login, a user can participate in chat or discussion. The users can change their display picture after logging in the application. Before starting the explanation of functionality, please take a short overview about the SignalR as follows.

Overview of SignalR

ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications, i.e., the ability to have server code push the content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.

SignalR can be used to add any sort of "real-time" web functionality to your ASP.NET application. While chat is often used as an example, you can do a whole lot more. Any time a user refreshes a web page to see the new data, or the page implements long polling to retrieve the new data, it is a candidate for using SignalR.

Targeted Audience

The targeted audience is people with basic knowledge of ASP.NET and C#.


Things to do:

  • Make an ASP.NET C# WebForm application.
  • Add the following packages through NuGet Package Manager.
    1. Bootstrap
    2. jQuery
    3. Font-awesome
    4. Microsoft.AspNet.SignalR
  • Create Startup.cs
  • Create ChatHub.cs
  • Create Login WebForm
  • Create Register WebFrom
  • Create Chat WebForm
  • Create a Database in SQL Server
  • Code

Create a New ASP.NET Web Project in C# and give it a suitable name as I gave the project name “SignalRChat”.

Image 1

After creating the project, now, add Packages through the NuGet Package Manager as shown in the following image:

Image 2

Image 3

The package Console Manager will open. You can add any package just by writing Package Name and press Enter button. It will get downloaded and installed in your project. You can see the reference files in your project references or you can see the package files in their respective project directories.

Install Packages

  1. PM> Install-Package bootstrap -Version 3.3.7
  2. PM> Install-Package FontAwesome -Version 4.7.0
  3. PM> Install-Package jQuery -Version 3.2.1
  4. PM> Install-Package Microsoft.AspNet.SignalR -Version 2.2.2

After the successful installation of the above packages, the above DLLs or packages are installed into your project. You can see the Reference files in your project solution.

Image 4

Other Reference files like Microsoft.owin are dependency files of Microsoft.AspNet.SignalR namespace. Since our application is OWN based application, so we have to create a class “Startup.cs”. In this file, the components for the application pipeline are added. The OWIN attribute which specifies the type of property specifying the project's start up and the configuration method, sets up the SignalR mapping for the App. The code for the “Startup.cs” is given below:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
    public class Startup
        public void Configuration(IAppBuilder app)

Now, create a database. As we are going to create a registration and login system, we will use login details from database for login. When a user gets registered, it will store the User details into the database and use the same while the user logs in to the application.

Create database:

Create Database SignalRdb 

Create a Table and insert a record for admin user:

USE [SignalRdb]


CREATE TABLE [dbo].[tbl_Users](
[ID] [int] IDENTITY(1,1) NOT NULL,
       [UserName] [varchar](50) NULL,
       [Email] [varchar](50) NULL,
       [Password] [varchar](50) NULL,
       [Photo] [varchar](50) NULL,

insert into [dbo].[tbl_Users] _

Here, I am skipping the explanation of connection of SQL Server database; I hope you know the connectivity of database. You will get everything in the source code that I have attached.

After creating the database, create a new WebForm Register Page (Register.aspx). Here, I am using ready CSS file to design my register page. The page will look like the below image:

Image 5

Code for Register.cs:

public partial class Register : System.Web.UI.Page
     ConnClass ConnC = new ConnClass();
     protected void Page_Load(object sender, EventArgs e)

     protected void btnRegister_ServerClick(object sender, EventArgs e)
         string Query = "insert into tbl_Users(UserName,Email,Password)Values
         string ExistQ = "select * from tbl_Users where Email='"+txtEmail.Value+"'";
         if (!ConnC.IsExist(ExistQ))
             if (ConnC.ExecuteQuery(Query))
                 ScriptManager.RegisterStartupScript(this, GetType(), "Message",
                 "alert('Congratulations!! You have successfully registered..');", true);
                 Session["UserName"] = txtName.Value;
                 Session["Email"] = txtEmail.Value;
             ScriptManager.RegisterStartupScript(this, GetType(), "Message",
             "alert('Email is already Exists!! Please Try Different Email..');", true);

Now, create a Login Page (Login.aspx). Here, I am using ready CSS file to design my Login page. The page will look like this:

Image 6

public partial class Login : System.Web.UI.Page
    //Class Object
    ConnClass ConnC = new ConnClass();
    protected void Page_Load(object sender, EventArgs e)


    protected void btnSignIn_Click(object sender, EventArgs e)
        string Query = "select * from tbl_Users where Email='" +
               txtEmail.Value + "' and Password='" + txtPassword.Value + "'";
        if (ConnC.IsExist(Query))
            string UserName = ConnC.GetColumnVal(Query, "UserName");
            Session["UserName"] = UserName;
            Session["Email"] = txtEmail.Value;
            txtEmail.Value = "Invalid Email or Password!!";

Create new WebForm “Chat.aspx” - this is the main page of our application, after successful login, this page will display to the user. And here, user can chat with other online users. And there is also an option “Change Profile Picture” so user can change his profile picture, which displays in chat while chatting, other users can also see his profile image.

Now create Hub Class, create a new class named this class “ChatHub.cs”, so this is the hub class, here we are creating function which we are calling in “Chat.aspx page” by using jquery.

  public class ChatHub :Hub
        static List<Users> ConnectedUsers = new List<Users>();
        static List<Messages> CurrentMessage = new List<Messages>();
        ConnClass ConnC = new ConnClass();

        public void Connect(string userName)
            var id = Context.ConnectionId;
            if (ConnectedUsers.Count(x => x.ConnectionId == id) == 0)
                string UserImg = GetUserImage(userName);
                string logintime = DateTime.Now.ToString();
                ConnectedUsers.Add(new Users { ConnectionId = id, 
                    UserName = userName, UserImage = UserImg, LoginTime = logintime });

                // send to caller
                Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage);

                // send to all except caller client
                Clients.AllExcept(id).onNewUserConnected(id, userName, UserImg, logintime);

In Design Page, we are calling this function. Here, I am giving you only one example, there are many functions that we have created on Hub class file and calling these functions in design page.

$(function () {

           // Declare a proxy to reference the hub.
           var chatHub = $.connection.chatHub;
           // Start Hub
           $.connection.hub.start().done(function () {



In the above JQuery function, we are initializing hub connection and we are writing rest of the functions in hub start function. See the below function. In this function, we have called function from Hub class that is “ChatHub.cs” and pass values through the parameters:

// Calls when user successfully logged in
            chatHub.client.onConnected = function (id, userName, allUsers, messages, times) {

                // Add All Users
                for (i = 0; i < allUsers.length; i++) {

                    AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName, 
                            allUsers[i].UserImage, allUsers[i].LoginTime);

                // Add Existing Messages
                for (i = 0; i < messages.length; i++) {
                    AddMessage(messages[i].UserName, messages[i].Message, 
                               messages[i].Time, messages[i].UserImage);                 

This method is used to send message. Here, we are passing user name, message, and message time and we are getting user image by user name that we have stored in the database, if user does not have any image so here we are setting a dummy image for kind of users.

public void SendMessageToAll(string userName, string message, string time)
           string UserImg = GetUserImage(userName);
            // store last 100 messages in cache
            AddMessageinCache(userName, message, time, UserImg);

            // Broad cast message
            Clients.All.messageReceived(userName, message, time, UserImg);


Images stored in Project directory, here we have to assign a directory for user images, the images names will be stored in database and image will stored in “images/DP/” directory.

public string GetUserImage(string username)
           string RetimgName = "images/dummy.png";
               string query = "select Photo from tbl_Users where UserName='" + username + "'";
               string ImageName = ConnC.GetColumnVal(query, "Photo");

               if (ImageName != "")
                   RetimgName = "images/DP/" + ImageName;
           catch (Exception ex)
           { }
           return RetimgName;

The SendMessageToAll method is requested from the client with the parameters after the connection is set on the client side and once the server receives the request, it processes and sends back the response to the client. There is a method which appends message into HTML DIV and displays on the UI to the client. The client side code would look like below:

function AddMessage(userName, message, time, userimg) {

           var CurrUser = $('#hdUserName').val();
           var Side = 'right';
           var TimeSide = 'left';

           if (CurrUser == userName) {
               Side = 'left';
               TimeSide = 'right';

           var divChat = '<div class="direct-chat-msg ' + Side + '">' +
               '<div class="direct-chat-info clearfix">' +
               '<span class="direct-chat-name pull-' +
                        Side + '">' + userName + '</span>' +
               '<span class="direct-chat-timestamp pull-' + TimeSide + '"">' +
                time + '</span>' +
               '</div>' +

               ' <img class="direct-chat-img" src="' +
                  userimg + '" alt="Message User Image">' +
               ' <div class="direct-chat-text" >' + message + '</div> </div>';


           var height = $('#divChatWindow')[0].scrollHeight;

Users can set their profile picture and also can change their picture so here is an option to change profile picture for users, here we have used Bootstrap Modal Popup.

Image 7


The final output will look like below:

Image 8


Here, we learned the integration of SignalR and Nuget Package in project that simplify the work of our project, and also web page designing using Bootstrap. Basically, this is just a simple Chat application, which you can use to chat with your friends, SignalR is not just this much. There are a lot of other effective uses of SignalR. So this is the first part of “SignalR Chat App” Tutorial. I will explain the integration of private chat in my next article, we are going to add some more effective features of chat in our next article.

Hope this will help you and you would like this article, I have attached Project source code. You can download the source code for your reference and to see the complete source. Thank you for reading...

Please give your valuable feedback in the comments section below.


  • 20th December, 2017: Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Altaf Ansari
Software Developer Prothious Engineering Services
India India
Team Leader .Net Developer, Working on Microsoft Technology Asp.Net, C#, SQL, Windows Application, Web Application.

Achievements :

13th January 2018 - Article of the Day - ASP.NET Community (SignalR Chat App With ASP.NET WebForm And BootStrap - Part One)

14th February 2018 - Article of the Day - ASP.NET Community (SignalR Chat App With ASP.NET WebForm And BootStrap - Part Two)

3rd March 2018 - Article of the Day - ASP.NET Community (SignalR Chat App With ASP.NET WebForm And BootStrap - Part Three)

Comments and Discussions

Questionwhat can i do to send an image as a message Pin
khushna9721-Jun-20 21:55
Memberkhushna9721-Jun-20 21:55 
Questiondefinition issues with 'UserName' and 'UserImage' Pin
Member 1123037227-Nov-19 16:41
MemberMember 1123037227-Nov-19 16:41 
QuestionLoose and uninformative Pin
AtarashiiJoey2-Nov-18 1:22
MemberAtarashiiJoey2-Nov-18 1:22 
QuestionWhen open new IE Tab, it don't know that already login on first IE Tab Pin
Member 1208234914-Sep-18 6:08
MemberMember 1208234914-Sep-18 6:08 
AnswerRe: When open new IE Tab, it don't know that already login on first IE Tab Pin
Altaf Ansari18-Sep-18 22:28
MemberAltaf Ansari18-Sep-18 22:28 
QuestionSignalR and JQuery Library Pin
Member 138568104-Jun-18 23:50
MemberMember 138568104-Jun-18 23:50 
AnswerRe: SignalR and JQuery Library Pin
Altaf Ansari18-Sep-18 22:29
MemberAltaf Ansari18-Sep-18 22:29 
QuestionConnClass reference is not being added Pin
Member 1379332422-Apr-18 23:17
MemberMember 1379332422-Apr-18 23:17 
Questionhow to integrate VS 2013 Pin
jerin_shalini20-Apr-18 0:33
professionaljerin_shalini20-Apr-18 0:33 
AnswerRe: how to integrate VS 2013 Pin
Altaf Ansari18-Sep-18 22:31
MemberAltaf Ansari18-Sep-18 22:31 
Questionhow can i use signalr in 3 tier architecture Pin
Member 1286765621-Mar-18 22:57
MemberMember 1286765621-Mar-18 22:57 
PraiseGood article... Pin
Uttari Anthony8-Jan-18 17:54
MemberUttari Anthony8-Jan-18 17:54 
GeneralRe: Good article... Pin
Altaf Ansari8-Jan-18 17:54
MemberAltaf Ansari8-Jan-18 17:54 
PraiseNice article Pin
Member 121937718-Jan-18 3:06
MemberMember 121937718-Jan-18 3:06 
GeneralRe: Nice article Pin
Altaf Ansari18-Sep-18 22:32
MemberAltaf Ansari18-Sep-18 22:32 
QuestionDangerous Sql Query Pin
Herman<T>.Instance5-Jan-18 1:22
MemberHerman<T>.Instance5-Jan-18 1:22 
AnswerRe: Dangerous Sql Query Pin
Altaf Ansari5-Jan-18 2:22
MemberAltaf Ansari5-Jan-18 2:22 
GeneralRe: Dangerous Sql Query Pin
Kevin Marois19-Sep-18 7:49
professionalKevin Marois19-Sep-18 7:49 
GeneralRe: Dangerous Sql Query Pin
Altaf Ansari19-Sep-18 20:05
MemberAltaf Ansari19-Sep-18 20:05 
Questionsome query about your signalr chat Pin
Mou_kol20-Dec-17 20:29
MemberMou_kol20-Dec-17 20:29 
AnswerRe: some query about your signalr chat Pin
Altaf Ansari20-Dec-17 22:07
MemberAltaf Ansari20-Dec-17 22:07 
QuestionHave a 5 Pin
Dewey20-Dec-17 12:22
MemberDewey20-Dec-17 12:22 
AnswerRe: Have a 5 Pin
Altaf Ansari18-Sep-18 22:33
MemberAltaf Ansari18-Sep-18 22:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.