ASP.NET Core is a powerful framework for building web applications, and SignalR is a library that makes it easy to add real-time functionality to your app. In this blog post, we’ll explore how to use SignalR to add real-time functionality to an ASP.NET Core app.
First, let’s define what we mean by “real-time functionality.” In the context of web development, this typically refers to the ability of the server to push updates to connected clients without the need for the client to continuously poll the server. This can be useful in a variety of situations, such as chat applications, real-time dashboards, and online multiplayer games.
SignalR is a library for ASP.NET Core that makes it easy to add real-time functionality to your app. It abstracts away the details of the underlying transport protocol (e.g. WebSockets, Server-Sent Events, etc.) and provides a simple API for sending messages between the server and connected clients.
To get started with SignalR, you’ll need to install Microsoft.AspNetCore.SignalR package. You can do this using the NuGet Package Manager in Visual Studio or by running the following command in the Package Manager Console:
Install-Package Microsoft.AspNetCore.SignalR
Once the package is installed, you’ll need to add SignalR to your app’s services and configure it in the Startup class. Here’s an example of how to do this:
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chat");
});
}
In this example, we’re mapping the ChatHub class to the “/chat” endpoint, which means that clients can connect to the hub at that URL.
The next step is to create a Hub class. This is where you’ll define the methods that can be called from the client and the methods that can be called from the server. Here’s an example of a simple ChatHub class:
public class ChatHub : Hub
{
public Task SendMessage(string message)
{
return Clients.All.SendAsync("ReceiveMessage", message);
}
}
In this example, we have a single method, SendMessage, which can be called by the client. When this method is called, it sends a message to all connected clients by calling the SendAsync method on the Clients object.
On the client side, you can connect to the hub using the SignalR JavaScript library. Here’s an example of how to do this:
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chat")
.build();
connection.on("ReceiveMessage", (message) => {
console.log(message);
});
connection.start().catch(err => console.error(err.toString()));
In this example, we’re creating a new HubConnection object and configuring it to connect to the “/chat” endpoint. We’re also setting up an event handler for the “ReceiveMessage” event, which will be called whenever a message is received from the server.
Message method on the server by calling invoke the method on the connection object.
connection.invoke("SendMessage", "Hello from the client!").catch(err => console.error(err.toString()));
That’s it! You now have a basic real-time chat application using SignalR and ASP.NET Core. You can expand on this example by adding more functionality, such as displaying a list of connected users or adding authentication and authorization to the chat.
SignalR also supports other types of connections besides just hub connections, such as Persistent Connections and Streaming. Persistent Connections provide a lower-level API that allows you to handle connection management manually. Streaming allows you to send large amounts of data between the server and the client.
In conclusion, SignalR is a powerful library for adding real-time functionality to an ASP.NET Core app. It abstracts away the details of the underlying transport protocol and provides a simple API for sending messages between the server and connected clients. With SignalR, you can easily build real-time web apps such as chat applications, real-time dashboards, and online multiplayer games.