SHASHANGKA SHEKHAR'S BLOG

Author, TechWriter

User Specific Notifications Using ASP.NET MVC & SignalR

Hits: 1584

In this post we are going to explore how to implement user based notification using ASP.Net MVC & SignalR.

In case if you are new to SignalR the please get some basics here: https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/introduction-to-signalr

Why SignalR?

SignalR provides “real-time” web functionality in our application using Javascript function call in client browser from server (Server Sent Events). It has several connection management like

  • connect/disconnect/reconnect events,
  • grouping connections,
  • authorization etc

Go to http://signalr.net for more.

We will focus on:

  1. Creating a new ASP.Net MVC Web Application
  2. Add SignalR
  3. Creating Hub
  4. Enable SignalR
  5. Database Modification
  6. Send specific user Notification using SignalR

Create ASP.Net MVC Web Application:

Open Visual Studio goto > File >New Project Choose ASP.Net MVC application

Choose a template in my case I have used MVC. Check Web API reference then hit ok button, that’s it. Build & run the application for first time.

Add SignalR:

Get it on NuGet! Right click the project > Manage NuGet package > Browse to install

Browse package then install to application, it’ll automatically done the rest.

OR Install using package manager console

Install-Package Microsoft.AspNet.SignalR

Creating Hub:

Add New Hub Class, Name it NotificationHub.cs

Enable SignalR:

Startup.cs

Layout page

Test SignalR

Run the application go to url modify by /signalr/hubs. This will show the magic SignalR JavaScript Library with current version like below screenshot.

In Browser Console it’ll show message about Hub Connection.

 

Database Modification:

Create new database then modify connection string in web.config file. Restore database from attached script file in App_Folder. We need to create a table to store Notifications.

Send specific user Notification using SignalR:

In this section we will work with view to send notification to specific user.

Index.cshtml:

Javascript:

API:

Modify Hub: We need to add additional methods in our Hub class.

Finally the Hub:

Broadcast to Client

Call to Server

Finally Client Script:

Output:

Source Code: I’ve uploaded the full source code to download/clone @github, Hope this will help 🙂

8 Comments

Post a comment