.NET Core SignalR Integration with Example
Updated on:
What is SignalR?
SignalR is a real-time communication library from Microsoft for ASP.NET Core. It allows server-side code to push content to connected clients instantly using WebSockets, Server-Sent Events, or Long Polling as a fallback.
Official documentation: SignalR Overview - Microsoft Docs
Why Use SignalR in .NET Core?
- Real-time updates without polling
- Built-in support in .NET Core
- Scales well with Azure SignalR Service
- Perfect for chat apps, live dashboards, or gaming
Step-by-Step: SignalR Integration Example in .NET Core
1. Create a new ASP.NET Core Project
dotnet new webapp -n SignalRDemo
2. Install SignalR NuGet Package
dotnet add package Microsoft.AspNetCore.SignalR
3. Create a SignalR Hub
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
4. Register SignalR in Startup.cs
// In Program.cs or Startup.cs depending on your .NET Core version
builder.Services.AddSignalR();
app.MapHub<ChatHub>("/chathub");
5. Add SignalR Client to HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.5/signalr.min.js"></script>
<script>
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.build();
connection.on("ReceiveMessage", function (user, message) {
console.log(user + ": " + message);
});
connection.start().then(function () {
connection.invoke("SendMessage", "User1", "Hello from client!");
});
</script>
Bonus: SignalR with Angular or React
SignalR integrates well with modern JavaScript frameworks. See how to use it with:
Conclusion
Integrating SignalR with .NET Core enables seamless real-time communication in your web apps. With minimal setup, you can create chat systems, real-time notifications, and live dashboards. Try it out in your next project!
FAQs
What protocol does SignalR use?
SignalR prefers WebSockets and falls back to Server-Sent Events or Long Polling.
Is SignalR free?
Yes, SignalR is open-source and free to use. Azure SignalR Service has a free tier and paid plans.
Can I use SignalR in Blazor?
Yes, SignalR is supported in both Blazor Server and Blazor WebAssembly apps.
Comments
Post a Comment