Easily Create A Real-time Application With Blazor And SignalR

Introduction


SignalR is a library for ASP.NET developers to simplify the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data. Chat application is often used as SignalR example, but here we will see a small book application, where we can have all the CRUD operations.
 
Blazor is a framework built by Microsoft for creating interactive client-side web UI with .NET codebase. We can write both client-side and server-side code in C#.NET itself. There are two hosting models available for Blazor. Blazor Server and Blazor WebAssembly. Blazor Server for production was already available. Recently Microsoft released the production version of Blazor WebAssembly also.

Create Blazor WebAssembly app with Visual Studio 2019


We can create a web application with Visual Studio 2019 using Blazor WebAssembly template. Please select the “ASP.NET Core hosted” option also.
 
 
 
If you look the solution structure, we can see 3 different projects are created by default.
 
 
As we are creating a Book app, add a “Book” class in “Shared” project.
 
Book.cs
  1. namespace BlazorSignalR.Shared  
  2. {  
  3.     public class Book  
  4.     {  
  5.         public string Id { getset; }  
  6.         public string Isbn { getset; }  
  7.         public string Name { getset; }  
  8.         public string Author { getset; }  
  9.         public double Price { getset; }  
  10.     }  
  11. }  
We have five properties in the Book class.
 
We can install “Microsoft.AspNetCore.SignalR.Client” library using NuGet package manager in “Client” project. This project library is already added as a dependency in “Server” project. Hence, we can use SignalR library in the Server project as well.
 
We must register the SignalR component inside the “ConfigureServices” method of Startup class (Server project).
 
 
  1. public void ConfigureServices(IServiceCollection services)  
  2.        {  
  3.   
  4.            services.AddControllersWithViews();  
  5.            services.AddRazorPages();  
  6.            services.AddSignalR();  
  7.            services.AddResponseCompression(opts =>  
  8.            {  
  9.                opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(  
  10.                    new[] { "application/octet-stream" });  
  11.            });  
  12.   
  13.         }  
Create a “BroadcastHub” class inside a new “Hubs” folder in Server project and inherit “Hub“ class from SignalR library.
 
BroadcastHub.cs
  1. using Microsoft.AspNetCore.SignalR;  
  2. using System.Threading.Tasks;  
  3.   
  4. namespace BlazorSignalR.Server.Hubs  
  5. {  
  6.     public class BroadcastHub : Hub  
  7.     {  
  8.         public async Task SendMessage()  
  9.         {  
  10.             await Clients.All.SendAsync("ReceiveMessage");  
  11.         }  
  12.     }  
  13. }  
We have added a “SendMessage” method in the above class. You can give any name for this method. It will be used to send and receive push notification using SignalR hub.
 
We can add the endpoints for BroadcastHub class in the Configure method of Startup class. We named it as “broadcastHub”. This will be used in our Razor components later in Client project.
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  2.         {  
  3.             if (env.IsDevelopment())  
  4.             {  
  5.                 app.UseDeveloperExceptionPage();  
  6.                 app.UseWebAssemblyDebugging();  
  7.             }  
  8.             else  
  9.             {  
  10.                 app.UseExceptionHandler("/Error");  
  11.             }  
  12.   
  13.             app.UseBlazorFrameworkFiles();  
  14.             app.UseStaticFiles();  
  15.   
  16.             app.UseRouting();  
  17.   
  18.             app.UseEndpoints(endpoints =>  
  19.             {  
  20.                 endpoints.MapRazorPages();  
  21.                 endpoints.MapControllers();  
  22.                 endpoints.MapHub<BroadcastHub>("/broadcastHub");  
  23.                 endpoints.MapFallbackToFile("index.html");  
  24.             });  
  25.         }  
We can create a “BooksController” class for CRUD operations under Controllers folder using Scaffolding template.
 
 
 
We have used scaffolding with entity framework template. So that, all the methods for CRUD operations has been created automatically. But we have slightly changed the “PostBook” method for our purpose. Please use the below code.
 
BooksController.cs
  1. using BlazorSignalR.Server.Data;  
  2. using BlazorSignalR.Shared;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using Microsoft.EntityFrameworkCore;  
  5. using System;  
  6. using System.Collections.Generic;  
  7. using System.Linq;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace BlazorSignalR.Server.Controllers  
  11. {  
  12.     [Route("api/[controller]")]  
  13.     [ApiController]  
  14.     public class BooksController : ControllerBase  
  15.     {  
  16.         private readonly BooksDbContext _context;  
  17.   
  18.         public BooksController(BooksDbContext context)  
  19.         {  
  20.             _context = context;  
  21.         }  
  22.   
  23.         // GET: api/Books  
  24.         [HttpGet]  
  25.         public async Task<ActionResult<IEnumerable<Book>>> GetBook()  
  26.         {  
  27.             return await _context.Book.ToListAsync();  
  28.         }  
  29.   
  30.         // GET: api/Books/5  
  31.         [HttpGet("{id}")]  
  32.         public async Task<ActionResult<Book>> GetBook(string id)  
  33.         {  
  34.             var book = await _context.Book.FindAsync(id);  
  35.   
  36.             if (book == null)  
  37.             {  
  38.                 return NotFound();  
  39.             }  
  40.   
  41.             return book;  
  42.         }  
  43.   
  44.         // PUT: api/Books/5  
  45.         // To protect from overposting attacks, enable the specific properties you want to bind to, for  
  46.         // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.  
  47.         [HttpPut("{id}")]  
  48.         public async Task<IActionResult> PutBook(string id, Book book)  
  49.         {  
  50.             if (id != book.Id)  
  51.             {  
  52.                 return BadRequest();  
  53.             }  
  54.   
  55.             _context.Entry(book).State = EntityState.Modified;  
  56.   
  57.             try  
  58.             {  
  59.                 await _context.SaveChangesAsync();  
  60.             }  
  61.             catch (DbUpdateConcurrencyException)  
  62.             {  
  63.                 if (!BookExists(id))  
  64.                 {  
  65.                     return NotFound();  
  66.                 }  
  67.                 else  
  68.                 {  
  69.                     throw;  
  70.                 }  
  71.             }  
  72.   
  73.             return NoContent();  
  74.         }  
  75.   
  76.         // POST: api/Books  
  77.         // To protect from overposting attacks, enable the specific properties you want to bind to, for  
  78.         // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.  
  79.         [HttpPost]  
  80.         public async Task<ActionResult> PostBook(Book book)  
  81.         {  
  82.             book.Id = Guid.NewGuid().ToString();  
  83.             _context.Book.Add(book);  
  84.             try  
  85.             {  
  86.                 await _context.SaveChangesAsync();  
  87.             }  
  88.             catch (DbUpdateException)  
  89.             {  
  90.                 if (BookExists(book.Id))  
  91.                 {  
  92.                     return Conflict();  
  93.                 }  
  94.                 else  
  95.                 {  
  96.                     throw;  
  97.                 }  
  98.             }  
  99.   
  100.             return Ok();  
  101.         }  
  102.   
  103.         // DELETE: api/Books/5  
  104.         [HttpDelete("{id}")]  
  105.         public async Task<ActionResult<Book>> DeleteBook(string id)  
  106.         {  
  107.             var book = await _context.Book.FindAsync(id);  
  108.             if (book == null)  
  109.             {  
  110.                 return NotFound();  
  111.             }  
  112.   
  113.             _context.Book.Remove(book);  
  114.             await _context.SaveChangesAsync();  
  115.   
  116.             return book;  
  117.         }  
  118.   
  119.         private bool BookExists(string id)  
  120.         {  
  121.             return _context.Book.Any(e => e.Id == id);  
  122.         }  
  123.     }  
  124. }  
We can notice that a new connection string is created in the appsettings.json file and registered the database connection context in “ConfigureServices” method of Startup class.
 
Open Package Manager Console from “Tools” -> “NuGet Package Manager” and use below NuGet command to create a migration script. We are using Entity framework code first approach in this application.
 
Add-migration Init
 
Above command will create a new class with current timestamp (Suffix as “_Init”), and it will be used for our data migration.
 
Use below NuGet command to update the database.
 
Update-database
 
If you look at the SQL Server Object Explorer, you can see that a new database is created with a “Book” table.
 
 

Create Razor Components in Client project


We can create the razor components for CRUD operations in Client project.
 
Add “ListBooks” component inside the “Pages” folder to display all book details from database using API get method.
 
ListBooks.razor
  1. @page "/listbooks"  
  2.   
  3. @using BlazorSignalR.Shared  
  4. @using Microsoft.AspNetCore.SignalR.Client  
  5.   
  6. @inject NavigationManager NavigationManager  
  7. @inject HttpClient Http  
  8.   
  9. <h2>Book Details</h2>  
  10. <p>  
  11.     <a href="/addbook">Create New Book</a>  
  12. </p>  
  13. @if (books == null)  
  14. {  
  15.     <p>Loading...</p>  
  16. }  
  17. else  
  18. {  
  19.     <table class='table'>  
  20.         <thead>  
  21.             <tr>  
  22.                 <th>Name</th>  
  23.                 <th>ISBN</th>  
  24.                 <th>Author</th>  
  25.                 <th>Price</th>  
  26.             </tr>  
  27.         </thead>  
  28.         <tbody>  
  29.             @foreach (var book in books)  
  30.             {  
  31.                 <tr>  
  32.                     <td>@book.Name</td>  
  33.                     <td>@book.Isbn</td>  
  34.                     <td>@book.Author</td>  
  35.                     <td>@book.Price</td>  
  36.                     <td>  
  37.                         <a href='/editbook/@book.Id'>Edit</a>  
  38.                         <a href='/deletebook/@book.Id'>Delete</a>  
  39.                     </td>  
  40.                 </tr>  
  41.             }  
  42.         </tbody>  
  43.     </table>  
  44. }  
  45.   
  46. @code {  
  47.     Book[] books;  
  48.     private HubConnection hubConnection;  
  49.   
  50.     protected override async Task OnInitializedAsync()  
  51.     {  
  52.   
  53.         hubConnection = new HubConnectionBuilder()  
  54.             .WithUrl(NavigationManager.ToAbsoluteUri("/broadcastHub"))  
  55.             .Build();  
  56.   
  57.         hubConnection.On("ReceiveMessage", () =>  
  58.         {  
  59.             CallLoadData();  
  60.             StateHasChanged();  
  61.         });  
  62.   
  63.         await hubConnection.StartAsync();  
  64.   
  65.         await LoadData();  
  66.     }  
  67.   
  68.     private void CallLoadData()   
  69.     {  
  70.         Task.Run(async () =>  
  71.         {  
  72.             await LoadData();  
  73.         });  
  74.     }  
  75.   
  76.     protected async Task LoadData()  
  77.     {  
  78.         books = await Http.GetFromJsonAsync<Book[]>("api/books");  
  79.         StateHasChanged();  
  80.     }  
  81.   
  82.     public bool IsConnected =>  
  83.         hubConnection.State == HubConnectionState.Connected;  
  84.   
  85.     public void Dispose()  
  86.     {  
  87.         _ = hubConnection.DisposeAsync();  
  88.     }  
  89. }  
If you look at the code, you can see that we have initialized a SignalR hub connection inside the “OnInitializedAsync” method and also navigated to the “broadcastHub” endpoint, that we have already registered in the Startup class.
 
 
Hub connection is listening for a new push message from Hub server and it will call the “CallLoadData” method. This method will again call the LoadData method and will get new or modified Book data from database using API get method. Whenever, we add or change a book record in another web client, it will be automatically reflected in this component. Hence, we will get real-time data.
 
Create a new razor component “AddBook” and add below code inside the component file.
 
AddBook.razor
  1. @page "/addbook"  
  2.   
  3. @using Microsoft.AspNetCore.SignalR.Client  
  4. @using BlazorSignalR.Shared  
  5.   
  6. @inject HttpClient Http  
  7. @inject NavigationManager NavigationManager  
  8.   
  9. <h2>Create Book</h2>  
  10. <hr />  
  11. <form>  
  12.     <div class="row">  
  13.         <div class="col-md-8">  
  14.             <div class="form-group">  
  15.                 <label for="Name" class="control-label">Name</label>  
  16.                 <input for="Name" class="form-control" @bind="@book.Name" />  
  17.             </div>  
  18.             <div class="form-group">  
  19.                 <label for="Department" class="control-label">ISBN</label>  
  20.                 <input for="Department" class="form-control" @bind="@book.Isbn" />  
  21.             </div>  
  22.             <div class="form-group">  
  23.                 <label for="Designation" class="control-label">Author</label>  
  24.                 <input for="Designation" class="form-control" @bind="@book.Author" />  
  25.             </div>  
  26.             <div class="form-group">  
  27.                 <label for="Company" class="control-label">Price</label>  
  28.                 <input for="Company" class="form-control" @bind="@book.Price" />  
  29.             </div>  
  30.         </div>  
  31.     </div>  
  32.     <div class="row">  
  33.         <div class="col-md-4">  
  34.             <div class="form-group">  
  35.                 <input type="button" class="btn btn-primary" @onclick="@CreateBook" value="Save" />  
  36.                 <input type="button" class="btn" @onclick="@Cancel" value="Cancel" />  
  37.             </div>  
  38.         </div>  
  39.     </div>  
  40. </form>  
  41.   
  42. @code {  
  43.   
  44.     private HubConnection hubConnection;  
  45.     Book book = new Book();  
  46.   
  47.     protected override async Task OnInitializedAsync()  
  48.     {  
  49.         hubConnection = new HubConnectionBuilder()  
  50.             .WithUrl(NavigationManager.ToAbsoluteUri("/broadcastHub"))  
  51.             .Build();  
  52.   
  53.         await hubConnection.StartAsync();  
  54.     }  
  55.   
  56.     protected async Task CreateBook()  
  57.     {  
  58.         await Http.PostAsJsonAsync("api/books", book);  
  59.         if (IsConnected) await SendMessage();  
  60.         NavigationManager.NavigateTo("listbooks");  
  61.     }  
  62.   
  63.     Task SendMessage() => hubConnection.SendAsync("SendMessage");  
  64.   
  65.     public bool IsConnected =>  
  66.         hubConnection.State == HubConnectionState.Connected;   
  67.   
  68.     public void Dispose()  
  69.     {  
  70.         _ = hubConnection.DisposeAsync();  
  71.     }  
  72.   
  73.     void Cancel()  
  74.     {  
  75.         NavigationManager.NavigateTo("listbooks");  
  76.     }  
  77. }       
 
Here also, we have initialized the hub connection inside the “OnInitializedAsync” method. If you look at the “CreateBook” method, you can notice that we have sent a notification to hub server after saving the data to database using API post method. Currently, we are not sending any additional message with this notification. We can send any object along with hub notification, but in our application, we have not implemented that. Whenever, we send a push notification from here, all the other open clients will receive the push notification and inside the ListBooks component. We have already implemented the code to load the data from database after receiving new notification.
We can create a new razor component “EditBook” and add below code inside the component file.
 
EditBook.razor
  1. @page "/editbook/{id}"  
  2.   
  3. @using Microsoft.AspNetCore.SignalR.Client  
  4. @using BlazorSignalR.Shared  
  5.   
  6. @inject HttpClient Http  
  7. @inject NavigationManager NavigationManager  
  8.   
  9. <h2>Edit Book</h2>  
  10. <hr />  
  11. <form>  
  12.     <div class="row">  
  13.         <div class="col-md-8">  
  14.             <div class="form-group">  
  15.                 <label for="Name" class="control-label">Name</label>  
  16.                 <input for="Name" class="form-control" @bind="@book.Name" />  
  17.             </div>  
  18.             <div class="form-group">  
  19.                 <label for="Department" class="control-label">ISBN</label>  
  20.                 <input for="Department" class="form-control" @bind="@book.Isbn" />  
  21.             </div>  
  22.             <div class="form-group">  
  23.                 <label for="Designation" class="control-label">Author</label>  
  24.                 <input for="Designation" class="form-control" @bind="@book.Author" />  
  25.             </div>  
  26.             <div class="form-group">  
  27.                 <label for="Company" class="control-label">Price</label>  
  28.                 <input for="Company" class="form-control" @bind="@book.Price" />  
  29.             </div>  
  30.         </div>  
  31.     </div>  
  32.     <div class="row">  
  33.         <div class="form-group">  
  34.             <input type="button" class="btn btn-primary" @onclick="@UpdateBook" value="Update" />  
  35.             <input type="button" class="btn" @onclick="@Cancel" value="Cancel" />  
  36.         </div>  
  37.     </div>  
  38. </form>  
  39.   
  40. @code {  
  41.   
  42.     private HubConnection hubConnection;  
  43.     [Parameter]  
  44.     public string id { getset; }  
  45.   
  46.     Book book = new Book();  
  47.   
  48.     protected override async Task OnInitializedAsync()  
  49.     {  
  50.         book = await Http.GetFromJsonAsync<Book>("api/books/" + id);  
  51.   
  52.         hubConnection = new HubConnectionBuilder()  
  53.             .WithUrl(NavigationManager.ToAbsoluteUri("/broadcastHub"))  
  54.             .Build();  
  55.   
  56.         await hubConnection.StartAsync();  
  57.     }  
  58.   
  59.     protected async Task UpdateBook()  
  60.     {  
  61.         await Http.PutAsJsonAsync("api/books/" + id, book);  
  62.         if (IsConnected) await SendMessage();  
  63.         NavigationManager.NavigateTo("listbooks");  
  64.     }  
  65.   
  66.     Task SendMessage() => hubConnection.SendAsync("SendMessage");  
  67.   
  68.     public bool IsConnected =>  
  69.         hubConnection.State == HubConnectionState.Connected;  
  70.   
  71.     public void Dispose()  
  72.     {  
  73.         _ = hubConnection.DisposeAsync();  
  74.     }  
  75.   
  76.     void Cancel()  
  77.     {  
  78.         NavigationManager.NavigateTo("listbooks");  
  79.     }  
  80. }       
Literally, we have used the same approach here also like AddBook component to send a push notification. After updating the data, hub will send a notification to all open clients and client will immediately refresh the data (in ListBooks component) after receiving the notification.
 
We can create a DeleteBook component and use below code.
 
DeleteBook.razor
  1. @page "/deletebook/{id}"  
  2.   
  3. @using Microsoft.AspNetCore.SignalR.Client  
  4. @using BlazorSignalR.Shared  
  5.   
  6. @inject HttpClient Http  
  7. @inject NavigationManager NavigationManager  
  8.   
  9. <h2>Delete</h2>  
  10. <p>Are you sure you want to delete this Book with Id :<b> @id</b></p>  
  11. <br />  
  12. <div class="col-md-4">  
  13.     <table class="table">  
  14.         <tr>  
  15.             <td>Name</td>  
  16.             <td>@book.Name</td>  
  17.         </tr>  
  18.         <tr>  
  19.             <td>ISBN</td>  
  20.             <td>@book.Isbn</td>  
  21.         </tr>  
  22.         <tr>  
  23.             <td>Author</td>  
  24.             <td>@book.Author</td>  
  25.         </tr>  
  26.         <tr>  
  27.             <td>Price</td>  
  28.             <td>@book.Price</td>  
  29.         </tr>  
  30.     </table>  
  31.     <div class="form-group">  
  32.         <input type="button" value="Delete" @onclick="@Delete" class="btn btn-primary" />  
  33.         <input type="button" value="Cancel" @onclick="@Cancel" class="btn" />  
  34.     </div>  
  35. </div>  
  36.   
  37. @code {  
  38.   
  39.     [Parameter]  
  40.     public string id { getset; }  
  41.   
  42.     Book book = new Book();  
  43.     private HubConnection hubConnection;  
  44.   
  45.     protected override async Task OnInitializedAsync()  
  46.     {  
  47.         book = await Http.GetFromJsonAsync<Book>("api/books/" + id);  
  48.   
  49.         hubConnection = new HubConnectionBuilder()  
  50.             .WithUrl(NavigationManager.ToAbsoluteUri("/broadcastHub"))  
  51.             .Build();  
  52.   
  53.         await hubConnection.StartAsync();  
  54.     }  
  55.   
  56.     Task SendMessage() => hubConnection.SendAsync("SendMessage");   
  57.   
  58.     public bool IsConnected =>  
  59.         hubConnection.State == HubConnectionState.Connected;  
  60.   
  61.     public void Dispose()  
  62.     {  
  63.         _ = hubConnection.DisposeAsync();  
  64.     }  
  65.   
  66.     protected async Task Delete()  
  67.     {  
  68.         await Http.DeleteAsync("api/books/" + id);  
  69.         if (IsConnected) await SendMessage();  
  70.         NavigationManager.NavigateTo("listbooks");  
  71.     }  
  72.   
  73.     void Cancel()  
  74.     {  
  75.         NavigationManager.NavigateTo("listbooks");  
  76.     }  
  77. }       
We have sent the push notification after deleting the data from database using API delete method.
 
We can add the navigation menu for Books data inside the “NavMenu” shared component.
 
NavMenu.razor
  1. <div class="top-row pl-4 navbar navbar-dark">  
  2.     <a class="navbar-brand" href="">BlazorSignalR</a>  
  3.     <button class="navbar-toggler" @onclick="ToggleNavMenu">  
  4.         <span class="navbar-toggler-icon"></span>  
  5.     </button>  
  6. </div>  
  7.   
  8. <div class="@NavMenuCssClass" @onclick="ToggleNavMenu">  
  9.     <ul class="nav flex-column">  
  10.         <li class="nav-item px-3">  
  11.             <NavLink class="nav-link" href="" Match="NavLinkMatch.All">  
  12.                 <span class="oi oi-home" aria-hidden="true"></span> Home  
  13.             </NavLink>  
  14.         </li>  
  15.         <li class="nav-item px-3">  
  16.             <NavLink class="nav-link" href="counter">  
  17.                 <span class="oi oi-plus" aria-hidden="true"></span> Counter  
  18.             </NavLink>  
  19.         </li>  
  20.         <li class="nav-item px-3">  
  21.             <NavLink class="nav-link" href="fetchdata">  
  22.                 <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data  
  23.             </NavLink>  
  24.         </li>  
  25.         <li class="nav-item px-3">  
  26.             <NavLink class="nav-link" href="listbooks">  
  27.                 <span class="oi oi-list-rich" aria-hidden="true"></span> Book Details  
  28.             </NavLink>  
  29.         </li>  
  30.     </ul>  
  31. </div>  
  32.   
  33. @code {  
  34.     private bool collapseNavMenu = true;  
  35.   
  36.     private string NavMenuCssClass => collapseNavMenu ? "collapse" : null;  
  37.   
  38.     private void ToggleNavMenu()  
  39.     {  
  40.         collapseNavMenu = !collapseNavMenu;  
  41.     }  
  42. }  
We have completed the entire coding part. We can run the application.
 
Click the “Books Details” navigation button and add a new book detail. You can open the same application inside a new browser or tab in the same time and notice that the browser will be automatically refreshed after saving the data in current browser.
 
 
 We can edit or delete the book data as well.
 
 

Conclusion


In this post, we have seen how to create a Real-time web application with Blazor WebAssembly and SignalR. We have created a simple Book data application with all CRUD operations and see that how the data is updated (automatically refreshed) in different browsers in real-time. We can see more exciting features of Blazor WebAssembly in upcoming articles. Please feel free to share your valuable feedback.