SignalR is a library that simplifies adding real-time web functionality to applications. It enables server-side code to push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data. This guide covers how to implement SignalR in an ASP.NET Core 8 Web API, along with best practices and detailed explanations.
SignalR provides an abstraction over a persistent connection between client and server. It supports various techniques for handling real-time communications, including WebSockets, Server-Sent Events, and Long Polling.
To set up SignalR in an ASP.NET Core application, you need to configure SignalR services and create a hub for handling real-time messages.
2.1 Configure Services Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
builder.Services.AddSignalR();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapHub<ChatHub>("/chatHub");
app.Run();
A hub is a class that serves as the main coordination point for SignalR. It is responsible for managing connections, groups, and messaging.
Example:
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
You can use SignalR in your controllers to send messages to connected clients.
3.1 Injecting IHubContext Example:
[ApiController]
[Route("[controller]")]
public class ChatController : ControllerBase
{
private readonly IHubContext<ChatHub> _hubContext;
public ChatController(IHubContext<ChatHub> hubContext)
{
_hubContext = hubContext;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] ChatMessage message)
{
await _hubContext.Clients.All.SendAsync("ReceiveMessage", message.User, message.Text);
return Ok();
}
}
public class ChatMessage
{
public string User { get; set; }
public string Text { get; set; }
}
SignalR allows you to manage client connections and handle events such as connection established, disconnected, and reconnected.
4.1 Handling Connections in Hub Example:
public class ChatHub : Hub
{
public override async Task OnConnectedAsync()
{
await Clients.Caller.SendAsync("OnConnected", Context.ConnectionId);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
await Clients.All.SendAsync("OnDisconnected", Context.ConnectionId);
await base.OnDisconnectedAsync(exception);
}
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
Advanced SignalR scenarios include using groups for broadcasting messages to specific subsets of clients and handling different types of messages.
5.1 Using Groups Example:
public class ChatHub : Hub
{
public async Task AddToGroup(string groupName)
{
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
await Clients.Group(groupName).SendAsync("ShowMessage", $"{Context.ConnectionId} has joined the group {groupName}.");
}
public async Task RemoveFromGroup(string groupName)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
await Clients.Group(groupName).SendAsync("ShowMessage", $"{Context.ConnectionId} has left the group {groupName}.");
}
public async Task SendMessageToGroup(string groupName, string message)
{
await Clients.Group(groupName).SendAsync("ReceiveMessage", message);
}
}
public class ChatHub : Hub
{
public async Task SendTextMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveTextMessage", user, message);
}
public async Task SendImageMessage(string user, string imageUrl)
{
await Clients.All.SendAsync("ReceiveImageMessage", user, imageUrl);
}
}
SignalR is a powerful library for adding real-time web functionality to your ASP.NET Core 8 Web API. By following this guide, you can set up SignalR, manage client connections, and handle real-time messaging efficiently. Implement best practices to ensure your SignalR implementation is secure, scalable, and performant.