find and solve || findandsolve.com
Please wait.....

Welcome back.






Before Read Terms of use

Live Chat in ASP.NET Core with C#

Live Chat in ASP.NET Core with C#

 

introduction

This artical provides an introduction to programming the server side of the ASP.NET SignalR and Hub with code example.
RPCs(remote procedure calls)from a server to connected clients and from clients to the server on  SignalR Hubs API. In server site code, we define methods that can be called by clients, and we call methods that run on the client. In client site code, we define methods that can be called from the server, and we call methods that run on the server. 


Step 1:

Open your mvc project as given below image

Live chat in asp.net core using mvc


Step 2: 

Right click your soluction name >  Add > and click New Item as giveb below.After selecting the project, a new project dialog will open in your computer given below image.Select  ASP.NET inside Visual Web menu from the left panel given.Then,select Startup Class from available Class  types list and then Put the name of the  Class Name as "Startup.css" and press Add.
 

Live chat in asp.net core using mvc


Step 3: 

Now, our project will be created. You can see the folder structure in Solution Explorer as shown in the given below image.
 

Live chat in asp.net core using mvc


Setup 4: 

Right click on Project solution and select Add > New Item. An "Add New Item" dialog box will open.Select  Class  from templates panel, and put the name as class. Press Add. This will add a Class inside Project Solution.You can see layout after add a Class file inside Solution Project as given below.
Live chat in asp.net core using mvc

 

Setp  5: 

Open Class.cs and put the following code . 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace DemoChat {     public class Class : Hub // "Hub" is abstract class  under Microsoft.AspNetCore.SignalR namespace     {         public async Task SendMessage(string message, string userId)         {             await Clients.Clients(userId).SendAsync("ReceiveMessage", message, Context.ConnectionId);             await Clients.Clients(Context.ConnectionId).SendAsync("OwnMessage", message.Trim());         }         public override Task OnConnectedAsync()         {             var connectionId = Context.ConnectionId;             Clients.All.SendAsync("OnlineUserList", connectionId);             return base.OnConnectedAsync();         }         public async Task OnlineUsers()         {             var connectionId = Context.ConnectionId;             await Clients.All.SendAsync("OnlineUserList", connectionId);         }
    } } 

Setup 6:

Open Startup.cs and put the following code . 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DemoChat {     public class Startup     {         public Startup(IConfiguration configuration)         {             Configuration = configuration;         }
        public IConfiguration Configuration { get; }
        // This method gets called by the runtime. Use this method to add services to the container.         public void ConfigureServices(IServiceCollection services)         {             services.Configure<CookiePolicyOptions>(options =>             {                 // This lambda determines whether user consent for non-essential cookies is needed for a given request.                 options.CheckConsentNeeded = context => true;                 options.MinimumSameSitePolicy = SameSiteMode.None;             });
            services.AddSignalR();             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);         }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)         {             if (env.IsDevelopment())             {                 app.UseDeveloperExceptionPage();             }             else             {                 app.UseExceptionHandler("/Home/Error");                 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.                 app.UseHsts();             }
            app.UseHttpsRedirection();             app.UseStaticFiles();             app.UseCookiePolicy();
            app.UseSignalR(routes =>             {                 routes.MapHub<Class>("/Index");             });
            app.UseMvc(routes =>             {                 routes.MapRoute(                     name: "default",                     template: "{controller=Home}/{action=Index}/{id?}");             });         }     } }  

 

Setup 7: 

Open Index.cshtml file from Home controller.Select Views > Home >index.cshtml and put this code in index.cshtml page.

@{
    ViewData["Title"] = "Home Page";
    string url = "https://cdn.jsdelivr.net/npm/@aspnet/signalr@1.0.0-rc1-update1/dist/browser/signalr.min.js";
}
<style>     .chat {         margin-top: auto;         margin-bottom: auto;     }
    .card {         height: 500px;         border-radius: 15px !important;         background-color: rgba(0,0,0,0.4) !important;     }
    .contacts_body {         padding: 0.75rem 0 !important;         overflow-y: auto;         white-space: nowrap;     }
    .msg_card_body {         overflow-y: auto;     }
    .card-header {         border-radius: 15px 15px 0 0 !important;         border-bottom: 0 !important;     }
    .card-footer {         border-radius: 0 0 15px 15px !important;         border-top: 0 !important;     }
    .container {         align-content: center;     }
    .search {         border-radius: 15px 0 0 15px !important;         background-color: rgba(0,0,0,0.3) !important;         border: 0 !important;         color: white !important;     }
        .search:focus {             box-shadow: none !important;             outline: 0px !important;         }
    .type_msg {         background-color: rgba(0,0,0,0.3) !important;         border: 0 !important;         color: white !important;         height: 60px !important;         overflow-y: auto;     }
        .type_msg:focus {             box-shadow: none !important;             outline: 0px !important;         }
    .attach_btn {         border-radius: 15px 0 0 15px !important;         background-color: rgba(0,0,0,0.3) !important;         border: 0 !important;         color: white !important;         cursor: pointer;     }
    .send_btn {         border-radius: 0 15px 15px 0 !important;         background-color: rgba(0,0,0,0.3) !important;         border: 0 !important;         color: white !important;         cursor: pointer;     }
    .search_btn {         border-radius: 0 15px 15px 0 !important;         background-color: rgba(0,0,0,0.3) !important;         border: 0 !important;         color: white !important;         cursor: pointer;     }
    .contacts {         list-style: none;         padding: 0;     }
        .contacts li {             width: 100% !important;             padding: 5px 10px;             margin-bottom: 15px !important;         }
    .active {         background-color: rgba(0,0,0,0.3);     }
    .user_img {         height: 70px;         width: 70px;         border: 1.5px solid #f5f6fa;     }
    .user_img_msg {         height: 40px;         width: 40px;         border: 1.5px solid #f5f6fa;     }
    .img_cont {         position: relative;         height: 70px;         width: 70px;     }
    .img_cont_msg {         height: 40px;         width: 40px;     }
    .online_icon {         position: absolute;         height: 15px;         width: 15px;         background-color: #4cd137;         border-radius: 50%;         bottom: 0.2em;         right: 0.4em;         border: 1.5px solid white;     }
    .offline {         background-color: #c23616 !important;     }
    .user_info {         margin-top: auto;         margin-bottom: auto;         margin-left: 15px;     }
        .user_info span {             font-size: 20px;             color: white;         }
        .user_info p {             font-size: 10px;             color: rgba(255,255,255,0.6);         }
    .video_cam {         margin-left: 50px;         margin-top: 5px;     }
        .video_cam span {             color: white;             font-size: 20px;             cursor: pointer;             margin-right: 20px;         }
    .msg_cotainer {         margin-top: auto;         margin-bottom: auto;         margin-left: 10px;         border-radius: 25px;         background-color: #82ccdd;         padding: 10px;         position: relative;     }
    .msg_cotainer_send {         margin-top: auto;         margin-bottom: auto;         margin-right: 10px;         border-radius: 25px;         background-color: #78e08f;         padding: 10px;         position: relative;     }
    .msg_time {         position: absolute;         left: 0;         bottom: -15px;         color: rgba(255,255,255,0.5);         font-size: 10px;     }
    .msg_time_send {         position: absolute;         right: 0;         bottom: -15px;         color: rgba(255,255,255,0.5);         font-size: 10px;     }
    .msg_head {         position: relative;     }
    #action_menu_btn {         position: absolute;         right: 10px;         top: 10px;         color: white;         cursor: pointer;         font-size: 20px;     }
    .action_menu {         z-index: 1;         position: absolute;         padding: 15px 0;         background-color: rgba(0,0,0,0.5);         color: white;         border-radius: 15px;         top: 30px;         right: 15px;         display: none;     }
        .action_menu ul {             list-style: none;             padding: 0;             margin: 0;         }
            .action_menu ul li {                 width: 100%;                 padding: 10px 15px;                 margin-bottom: 5px;             }
                .action_menu ul li i {                     padding-right: 10px;                 }
                .action_menu ul li:hover {                     cursor: pointer;                     background-color: rgba(0,0,0,0.2);                 }
    .justify-content-end {         background-color: #e09b1ecc;         color: white;         border-radius: 28px;     }
    .justify-content-start {         background-color: #ff005e6b;         color: white;         border-radius: 28px;     }
    ul {         list-style-type: none;     } </style> <script src="@url"></script> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ---------->
<div class="container-fluid h-100">
    <div class="row justify-content-center h-100">         <div class="col-md-4 col-xl-3 chat">             <div class="card mb-sm-3 mb-md-0 contacts_card">                 <div class="card-header">                     <div class="input-group">                         <input type="text" placeholder="Search..." name="" class="form-control search">                         <div class="input-group-prepend">                             <span class="input-group-text search_btn"><i class="fas fa-search"></i></span>                         </div>                     </div>                 </div>                 <div class="card-body contacts_body">                     <ui class="contacts">                         <div id="onlineUsersList"></div>                     </ui>                 </div>                 <div class="card-footer"></div>             </div>         </div>         <div class="col-md-8 col-xl-6 chat">             <div class="card">                 <div class="card-header msg_head">                     <div class="d-flex bd-highlight">                         <div class="user_info">                             <span>Chat with : <span id="chat-with-id"></span></span>                         </div>                     </div>                 </div>                 <div class="card-body msg_card_body">
                    <ul>                         <li id="messageListId"></li>                     </ul>                     @*<div id="receivedMessageId"></div>                         <div id="ownMessageId"></div>*@
                </div>                 <div class="card-footer">                     <div class="input-group">                         <div class="input-group-append">                             <span class="input-group-text attach_btn"><i class="fas fa-paperclip"></i></span>                         </div>
              <textarea name="" class="form-control type_msg" id="messageInput" placeholder="Type your message......">
                         </textarea>                         <div class="input-group-append">                             <span class="input-group-text send_btn" id="sendButton"><i class="fas fa-location-arrow"></i></span>                         </div>                     </div>                 </div>             </div>         </div>     </div>
    <div class="clearfix"></div> </div>
<script>     const connection = new signalR.HubConnectionBuilder()         .configureLogging(signalR.LogLevel.Debug)         .withUrl("https://localhost:44385/Index")         .configureLogging(signalR.LogLevel.Information)         .build();
    connection.start().then(() => {     });
    //define unique id for send message
    var receiverId = function (id) {         $('#chat-with-id').text(id);     }
    var sendMessage = function () {         const message = document.getElementById("messageInput").value;         connection.invoke("SendMessage", message, $('#chat-with-id').text()).then((result) => {
        }).catch(err => console.error(err.toString()));         event.preventDefault();
    }     document.getElementById("sendButton").addEventListener("click", event => {         sendMessage();     });
    $("#messageInput").keydown(function (e) {         if (e.keyCode == 13) {             sendMessage();             e.preventDefault();         }     });
    connection.on("OnlineUserList", (connectionId) => {         console.log(connectionId)         $('#onlineUsersList').append('<li class= "active" onclick=receiverId(' + "'" + connectionId + "'" + ')>' +             '<div class="d-flex bd-highlight">' +             '<div class="img_cont">' +             '<img src="http://www.findandsolve.com/icon.png" alt="find and solve" class="rounded-circle user_img">' +             '<span class="online_icon"></span></div>' +             '<div class="user_info">' +             '<span>Unique User Id</span>' +             '<p>' + connectionId + '</p></div> </div></li>'         )     });
    connection.on("OwnMessage", (message) => {         console.log('ownmessage');         console.log(message);         $('#messageListId').append('<li><div class="d-flex justify-content-end mb-4">' +             '<div class= ""msg_cotainer">' + message + '<span class= "msg_time_send" ></span></div >' +             '<div class="img_cont_msg">' +             '<img src="http://www.findandsolve.com/icon.png" alt="find and solve" class="rounded-circle user_img_msg"> </div> </div></li>')     });
    connection.on("ReceiveMessage", (message, senderId) => {         $('#chat-with-id').text(senderId);         $('#messageListId').append('<li><div class="d-flex justify-content-start mb-4">' +
            '<div class="img_cont_msg">' +             '<img src="http://www.findandsolve.com/icon.png" alt="find and solve" class="rounded-circle user_img_msg"> </div> ' +             '<div class= ""msg_cotainer">' + message + '<span class= "msg_time_send" ></span></div >' +             '</div ></li>')     });
</script>


Click here to  step by step video

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

1 Comments


Avatar for Rahul   Sharma
Rahul Sharma 1

Thank you so much.


Report Response