How to Build a Web App with SignalR in .NET Core?

Neo Infoway - WEB & Mobile Development Company | Festival | Neo | Infoway | Leading software Development company | Top Software development company in India
Document

How to Build a Web App with SignalR in .NET Core?

When it comes to building applications, one of the most well-liked libraries for.NET development company is SignalR. When developers design an application with real-time capability, they connect the server-side code content to every client as soon as it becomes available, instead of waiting for each client to request fresh data from the server. A bidirectional communication channel is provided by the SignalR communication service between the application’s client and server sides. Additionally, this service can be utilized for any online page or application that employs JavaScript or the.NET Framework 4.5, not just web applications.

Let’s read this blog to learn more about SignalR, including its requirements, how to use it with.NET Core, and other things.

What is SignalR?

One of the most widely used open-source tools that makes it easier for developers to add reliable, real-time online functionality to applications is ASP.NET Core SignalR. When a request is received, real-time web functionality enables the server-side code to provide the stream data to the client side instantaneously. This means that, rather than waiting for a new request from the client to send data back, the server-side code in a real-time enabled process is developed so that it quickly provides content or data to the connected client as soon as it becomes available.

Assume, for example, that the real-time application is a chat program. In this case, as soon as the client is available, the server provides data and messages to the client. Within the web application, messages can also be sent as push notifications using the SignalR service in this situation. In this case, SingalR creates a secure communication channel using encryption and a digital signature.

Some of the good candidates for SignalR service are :

Instant sales updates, company dashboards, and travel warnings are a few examples of dashboard and monitoring apps that make excellent candidates for SignalR.

.NET Core Applications can now require high-frequency updates from the server side thanks to SignalR.

These are the apps that require instantaneous real-time updates. Examples include applications for social networking, gaming, GPS, voting, auctions, and mapping

SignalR is responsible for apps like chat, travel alerts, games, social networks, and other apps that need real-time notifications.

The ideal applications for SignalR service are collaborative ones, like whiteboard and team meeting software.

An API is provided by the SignalR Net Core service to create remote procedure calls (RPCs) that transfer data from the server to the client. Server-side code can call different functions on clients through the use of remote procedure calls. In this instance, there are various supported platforms with corresponding client SDKs. As a result, different programming languages are invoked by the RPC call.

Features of SignalR Service

Using this method, messages can be transmitted concurrently to every client that is connected. With SignalR’s assistance, connection management is automatically handled by developers. It is possible to send messages to particular clients or groups using the SignalR service. One of this service’s most crucial features is the SignalR Hub protocol. This service can grow to accommodate more users.

Prerequisites

A few of the most important prerequisites for using ASP.NET Core SignalR are

Visual Studio Code:

VS Code, or Visual Studio Code, as it is commonly called. Microsoft is a software firm that developed this source code editor. With features like syntax highlighting, intelligent code completion, debugging, code refactoring, snippets, embedded Git, and more, it assists developers in writing client code. Any developer who wants to work with SignalR must be familiar with this source code editor

ASP.NET Core Web Application

The.NET development businesses leverage ASP.NET Core, an open-source, high-performance, cross-platform framework, to build contemporary, cloud-enabled apps. You must be able to write these kinds of apps in order to work with.NET Core SignalR.

Basic Knowledge of ASP.NET Core

An additional requirement for SignalR is a working grasp of the general-purpose software solution development framework,.NET Core. It makes it possible for .NET developers to construct a wide range of software applications, including gaming, cloud, mobile, web, desktop, and more. Additionally, in order to begin using the SignalR service, a basic understanding of this technology is necessary.

Steps to Implement SignalR in .Net Core

Let’s now examine the procedures that developers can use to configure and implement SignalR in ASP.NET Core:

Making a web application project with the ASP.NET Core framework is the first step. As you can see, in order to implement SignalR, we must first create a.NET web application. With that in mind, let’s walk through the process of defining methods.

Therefore, in order to use SignalR in ASP.NET Core, developers must first include the SignalR client library in the project for the web application. The instructions in the screenshot must be followed in order to add the SignalR client library.

In Solution Explorer, right-click the project, and select Add > Client-Side Library.

Add Client-Side Library dialog:

  • Select unpkg for Provider
  • Enter @microsoft/signalr@latest for Library.
  • Select Choose specific files, expand the dist/browser folder, and select signalr.js and signalr.min.js.
  • Set Target Location to wwwroot/js/signalr/.
  • Select Install.

After you are done with the installation process, it’s time to create SignalR Hub: ChatHub Class. To do so, follow the below given .NET SignalR code.

ChatHub.cs

                    
                        using Microsoft.AspNetCore.SignalR;
                        using System;
                        using System.Collections.Generic;
                        using System.Linq;
                        using System.Threading.Tasks;
                         
                        namespace SignalrImplementation.Models
                        {
                            public class ChatHub : Hub
                            {
                                public async Task SendMessage(string user, string message)
                                {
                                    await Clients.All.SendAsync("ReceiveMessage", user, message);
                                }
                            }
                        }
                        
                    
                    

Now after that, you need to add a service reference in the startup.cs’s ConfigureServices method. For that follow the below code.

startup.cs

                        
                            public void ConfigureServices(IServiceCollection services)
                            {
                            services.AddControllersWithViews();
                            services.AddSignalR();
                            }
                               
                        
                        

Now, you can add a chat hub class in the Configure method in startup.cs as shown in the below code.

                    
                        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
                        {
                          if (env.IsDevelopment())
                             {
                                app.UseDeveloperExceptionPage();
                              }
                           else
                              {
                                 app.UseExceptionHandler("/Home/Error");
                                 app.UseHsts();
                               }
                                  app.UseHttpsRedirection();
                                  app.UseStaticFiles();
                                  app.UseRouting();
                                  app.UseAuthorization();
                                  app.UseSignalR(routes =>
                                  {
                                      routes.MapHub("/chatHub");
                                  })
                                  app.UseEndpoints(endpoints =>
                                  {
                                      endpoints.MapControllerRoute(
                                          name: "default",
                                          pattern: "{controller=Home}/{action=Index}/{id?}");
                                  });
                        }
                        
                    
                    

After this, it’s time to create a new JavaScript file for HubConnection, as soon as in the below code.

chat.js

                        
                            const connection = new signalR.HubConnectionBuilder()
                            .withUrl("/chatHub")
                            .build();
                         
                        connection.on("ReceiveMessage", (user, message) => {
                            const msg = message.replace(/&/g, "&").replace(//g, ">");
                            const encodedMsg = user + " :: " + msg;
                            const li = document.createElement("li");
                            li.textContent = encodedMsg;
                            document.getElementById("messagesList").appendChild(li);
                        });
                         
                        connection.start().catch(err => console.error(err.toString()));
                          
                        
                        

Send the message

                    
                        document.getElementById("sendMessage").addEventListener("click", event => {
                            const user = document.getElementById("userName").value;
                            const message = document.getElementById("userMessage").value;
                            connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
                            event.preventDefault();
                        });
                         
                        
                    
                    

This was all about the logic that goes behind the implementation process. Now it’s time to create a User Interface for the Chat test.

GitHub Repository SignalR in .NET Core Example

Some of the best examples of GitHub repository SignalR samples in .NET Core are

  • MoveShape
  • ChatSample
  • AndroidJavaClient
  • WhiteBoard
  • PullRequestR
  • WindowsFormsSample

Frequently Asked Questions (FAQs)

SignalR is a real-time web communication library in .NET Core that enables bi-directional communication between the server and client. Unlike traditional HTTP-based communication, SignalR allows instant updates to clients without the need for constant polling, resulting in more responsive and interactive web applications.
SignalR offers several benefits, including real-time updates, reduced latency, improved user experience, simplified development of real-time features such as chat applications, live dashboards, and multiplayer games, and seamless integration with existing ASP.NET Core applications.
To begin building a web app with SignalR in .NET Core, you can start by creating a new ASP.NET Core project or adding SignalR to an existing project using the appropriate NuGet package. Then, define SignalR hubs to handle client-server communication, configure routing, and implement real-time features using JavaScript on the client-side.
SignalR hubs are server-side components that act as endpoints for client-server communication in SignalR applications. They manage connections, receive incoming messages from clients, and broadcast messages to connected clients. By defining hubs and methods within them, developers can create custom real-time functionality and handle client events.
Yes, SignalR is designed to scale and handle large numbers of concurrent connections efficiently. It supports backplane technologies like Redis, Azure Service Bus, and SQL Server to distribute messages across multiple server instances or nodes, allowing applications to scale horizontally and handle increased traffic and load.
SignalR provides built-in features for connection management, reconnection, and error handling, ensuring a reliable real-time communication experience. It automatically manages client connections, handles reconnections in case of network disruptions, and provides APIs for handling errors and monitoring connection status on the client and server sides.
Yes, security considerations are essential when using SignalR in web apps. Developers should implement authentication and authorization mechanisms to control access to SignalR hubs and prevent unauthorized users from accessing real-time features. Additionally, SignalR supports features like SSL/TLS encryption and CORS (Cross-Origin Resource Sharing) to enhance security and protect against common web vulnerabilities.

Web API in .NET 6.0 Tutorial: How to Build CRUD Operation

.NET 6.0 Web API Tutorial CRUD Operations - Neo Infoway

Introduction

This tutorial will show you how to build a.NET 6 Web API using Entity Framework core, SQL, and API endpoints. This will allow API clients to perform CRUD on data stored in the database.

We will use the database-first approach in our demo application. We will create a table first in the SQL database, and then we’ll use an entity framework for DBContext.

What is Web API?

Web APIs are a platform that allows the development of HTTP services. These services can be accessed from a variety of client-side software, such as mobile phones, web browsers, and desktop programs. It allows multiple applications to interact and exchange data.

Developers can create API functions that are available through HTTP requests. This function allows your clients to access and retrieve specific data that you have made available through the API.

Key features of API

  • Supports HTTP verbs such as GET, POST PUT DELETE etc. which allows clients perform different actions on data
  • Standard formats such as XML or JSON are supported by default, which helps exchange data between client and server.
  • API allows for the definition of custom data, allowing you to customize data according to client requirements
  • You can use APIs that are hosted either by yourself or by a third party.
  • This allows for easy authentication and authorization, which protects data and helps to control API operations.
  • API is the ideal platform to build RESTful web services. These services are flexible, scalable and easy to maintain.

Why do we need Web API?

Today, people use multiple devices, such as smartphones and tablets. To reach all users, you need more than just a web application. An API is needed to expose these data services to the various browsers and apps. By adding a web API, it is easier to connect the two ends and to update.

We need a Web API in this case to manage database interactions and the business logic between an Android app and an iOS application.

The Web API project allows all three applications to communicate with the database. It handles database interactions, and makes sure that the database cannot be accessed directly through websites or applications.

Web APIs are an important tool for modern application development because they allow secure and efficient communication among different devices and applications.

What’s new in .NET 6?

Take a look at the highlights.

Hot reloading

enables developers to make changes to the user interface even while the app is running. The changes are reflected instantly without having to rebuild or restart the application.

Minimal APIs

for developers to build lightweight services without needing templates or controllers, using extension methods of “Endpoint Convention Builder” in the Startup or Program class.

The middleware

logs HTTP request and response data like headers and body to improve debugging.

Blazer

is a web framework that allows you to build interactive web applications using c#. It has improved performance and event binding.

code structure

ASP.NET Core Program and Startup Classes has been simplified.

Support cloud-native

development through integration with Kubernetes or other cloud platforms.

Improved JSON Support

by introducing a new source generation

.NET Core

now supports GraphQL and gRPC APIs The.NET core is more secure thanks to the use of OpenSSL 3 as well as the support for Runtime Defense-in-Depth mitigations.

Supports single-file

applications without extracting for Windows, macOS and Linux

FileStream

has been rewritten to improve performance, particularly for file I/O.

Source code

is now improved with a new framework.

The.NET Runtime

has been improved to include garbage collection improvements, improved performance on ARM-based platforms, and hardware intrinsics.

Entity Frame Core

now supports Cosmos DB, and has a new LINQ query syntax to query nested JSON.

Visual Studio Tooling

has been improved with a new project template and integration with GitHub.

Prerequisites: Web API in .NET 6.0

  • Visual Studio 2022.
  • .NET SDK 6.0.
  • Sql-Server.

Create Project

Enter the project name ProductCrudAPI, select the location where you want to save your project, and click Next.

Select ..Net 6.0 (Long-term support) as a framework. Fill in the required information as shown in the below image, and click on Create.

Select .Net 6.0 (Long-term support) as a framework. Fill in the required information as shown in the below image, and click on Create.

Slide 1
Slide 2
Slide 3
Slide 4

Add NuGet Packages

To use the entity framework core in our project, we need to install two NuGet packages:

  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.EntityFrameworkCore.SqlServer

Follow the below instructions to install NuGet packages.

Right-click on Dependencies and select Manage NuGet Packages.

Slide 1
Slide 2
Slide 3

Microsoft.EntityFrameworkCore.Tools

Select the Browse tab and search for Microsoft.Entity Frame workCore.Tools and install its latest stable version.

Select.Net 6.0 (Long-term support) as a framework. Fill in the required information as shown

Microsoft.EntityFrameworkCore.SqlServer

Once the above package is installed, Search for Microsoft.Entity Frame workCore .SqlServer and install its latest stable version

Create SQL Database and Table.

Moving to the next section of the Web API in .NET 6.0 Tutorial, create New Database ProductDB in SQL, and execute the below script to create a Product table.

                    
                        USE [ProductDB]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Products](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](50) NOT NULL,
	[Description] [varchar](250) NULL,
	[Price] [decimal](18, 2) NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

                    
                   

Create DBContext and Model

Now, let’s move on to the next step of our web API tutorial, where we will create the DBContext and Model.

We are using the database first approach of the entity framework.

We have created a database table, and using the Scaffold-DbContext command of the entity framework; we will create the required class in the C# project.

Open Package Manager Console (Tool => Package Manager => Package Manager Console) and run below command:

Scaffold-DbContext “Server=SERVERNAME;Database=ProductDB;Integrated Security=True” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Replace SERVERNAME with your database server name.

Once this command is executed, the Model folder is created in the project solution. Model folder contains two files, ProductDBContext.cs and Product.cs.

ProductDBContext.cs is responsible for database interaction, and Product.cs is a model of the Products table.

Remove OnConfiguring() method from ProductDBContext.cs; it contains a database connection string and is not a good practice. We will add the connection string in the appsettings.json file.

Also remove ProductDBContext() constructor from this file.

Configure DB Connection

Add database connection string in appsettings.json file.

                    
                        {
                            "Logging": {
                              "LogLevel": {
                                "Default": "Information",
                                "Microsoft.AspNetCore": "Warning"
                              }
                            },
                            "AllowedHosts": "*",
                            "ConnectionStrings": {
                              "ProductDB": "Server=SERVERNAME;Database=ProductDB;Integrated Security=True;"
                            }
                          }
                          
                    
                  

Replace SERVERNAME with your database server name

As we are using the .Net 6 version, we need to make the required configuration changes in the Program.cs file. Microsoft eliminates Startup.cs in .Net 6. In the previous .Net version, Startup.cs was used for configurations.

Add below lines in Program.cs. Please refer to the below image for this.

                    
var connectionString = builder.Configuration.GetConnectionString("ProductDB");
builder.Services.AddDbContextPool(option =>
option.UseSqlServer(connectionString)
);

                    
                   

using Microsoft. EntityFrameworkCore;

using ProductAPI.Models;

Add Products Controller

Add a new empty API controller ProductsController.cs under the controller folder.

Add Methods in ProductsController

In ProductsController.cs, we will add GET, POST, PUT, and DELETE endpoints to achieve CRUD operations.

Please use the below code in your ProductsController.cs.

                        
                            using Microsoft.AspNetCore.Mvc; 
using Microsoft.EntityFrameworkCore; 
using ProductCRUDAPI.Models;

namespace ProductCRUDAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly ProductDBContext _context;

        public ProductsController(ProductDBContext context)
        {
            _context = context;
        }

        [HttpGet]
        public async Task <IEnumerable<Product >> Get()
        {
            return await _context.Products.ToListAsync();
        }

        [HttpGet("{id}")]
        public async Task <IActionResult> Get(int id)
        {
            if (id < 1)
                return BadRequest();
            var product = await _context.Products.FirstOrDefaultAsync(m => m.Id == id);
            if (product == null)
                return NotFound();
            return Ok(product);

        }

        [HttpPost]
        public async Task <IActionResult> Post(Product product)
        {
            _context.Add(product);
            await _context.SaveChangesAsync();
            return Ok();
        }

        [HttpPut]
        public async Task <IActionResult> Put(Product productData)
        {
            if (productData == null || productData.Id == 0)
                return BadRequest();

            var product = await _context.Products.FindAsync(productData.Id);
            if (product == null)
                return NotFound();
            product.Name = productData.Name;
            product.Description = productData.Description;
            product.Price = productData.Price;
            await _context.SaveChangesAsync();
            return Ok();
        }

        [HttpDelete("{id}")]
        public async Task <IActionResult> Delete(int id)
        {
            if (id < 1)
                return BadRequest();
            var product = await _context.Products.FindAsync(id);
            if (product == null) 
                return NotFound();
            _context.Products.Remove(product);
            await _context.SaveChangesAsync();
            return Ok();

        }
    }
}

                        
                    

Launch API

Finally, we are done with Web API in .NET 6.0 tutorial. Now, it’s time to launch this API, press F5. As we are using Swagger UI, we can execute API directly.

We can see GET, POST, PUT AND DELETE under Products. We can execute different API methods from this page itself.

Finally, we are done with Web API in .NET 6.0 tutorial. Now, it’s time to launch this API, press F5. As we are using Swagger UI, we can execute API directly. We can see GET, POST, PUT AND DELETE under Products. We can execute different API methods from this page itself.

}