[フレーム]

🚀 .NET Core API for SignalR Integration (with Example)

SignalR is a powerful library by Microsoft that enables real-time communication between server and client applications. It allows you to push data instantly to connected clients without needing them to refresh or repeatedly call the server.

In this article, we’ll cover:

  • What is SignalR?

  • Why use SignalR in .NET Core APIs

  • Step-by-step integration guide

  • A working code example

  • Useful external references

🧠 What is SignalR?

ASP.NET Core SignalR simplifies adding real-time web functionality to your applications. It uses WebSockets under the hood (and falls back to other techniques like Server-Sent Events or Long Polling if necessary).

Real-time web functionality means that server code can push content to connected clients instantly as it happens — perfect for chat apps, live dashboards, notifications, or collaborative editing.

⚡ Why Use SignalR with a .NET Core API?

Traditional APIs work on a request-response model. Clients must call the API repeatedly to get updates.

With SignalR, your API can notify clients instantly whenever data changes — reducing latency, bandwidth, and backend load.

Use cases

  • Live notifications (e.g., messages, alerts, stock updates)

  • Real-time dashboards (IoT, monitoring, etc.)

  • Collaborative apps (document editing, gaming)

  • Background job progress updates

🛠 Step-by-Step: Integrating SignalR in .NET Core API

🧩 Step 1. Create a .NET Core Web API Project

dotnet new webapi -n SignalRDemoAPI
cd SignalRDemoAPI

⚙️ Step 2. Install SignalR NuGet Package

dotnet add package Microsoft.AspNetCore.SignalR

🧱 Step 3. Create a Hub Class

Create a new folder Hubs and add a file NotificationHub.cs:

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace SignalRDemoAPI.Hubs
{
 public class NotificationHub : Hub
 {
 public async Task SendMessage(string user, string message)
 {
 await Clients.All.SendAsync("ReceiveMessage", user, message);
 }
 }
}

🧩 Explanation

  • Hub acts as a connection point between the server and the client.

  • The SendMessage method broadcasts a message to all connected clients.

🪄 Step 4. Configure SignalR in Program.cs

using SignalRDemoAPI.Hubs;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSignalR(); // Add SignalR service
var app = builder.Build();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
 endpoints.MapControllers();
 endpoints.MapHub<NotificationHub>("/notifyHub");
});
app.Run();

🧠 Here we:

  • Registered SignalR service using AddSignalR().

  • Mapped the NotificationHub to /notifyHub endpoint.

🧮 Step 5. Create an API Controller to Trigger Messages

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SignalRDemoAPI.Hubs;
namespace SignalRDemoAPI.Controllers
{
 [Route("api/[controller]")]
 [ApiController]
 public class NotificationController : ControllerBase
 {
 private readonly IHubContext<NotificationHub> _hubContext;
 public NotificationController(IHubContext<NotificationHub> hubContext)
 {
 _hubContext = hubContext;
 }
 [HttpPost("send")]
 public async Task<IActionResult> SendNotification(string user, string message)
 {
 await _hubContext.Clients.All.SendAsync("ReceiveMessage", user, message);
 return Ok(new { Status = "Message Sent", User = user, Message = message });
 }
 }
}

✅ This API endpoint can be called from anywhere (like another system or backend service) to broadcast messages in real time.

💻 Step 6. Create a Frontend Client (HTML Example)

Create a simple index.html in your project root:

<!DOCTYPE html>
<html>
<head>
 <title>SignalR Notification Client</title>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.5/signalr.min.js"></script>
</head>
<body>
 <h2>SignalR Demo</h2>
 <div id="messages"></div>
 <script>
 const connection = new signalR.HubConnectionBuilder()
 .withUrl("https://localhost:5001/notifyHub")
 .build();
 connection.on("ReceiveMessage", (user, message) => {
 const msg = document.createElement("div");
 msg.textContent = `${user}: ${message}`;
 document.getElementById("messages").appendChild(msg);
 });
 connection.start().catch(err => console.error(err.toString()));
 </script>
</body>
</html>

✅ Run your API and open the HTML file — you’ll see live messages appear when you hit the /api/notification/send endpoint from Postman.

🔥 Test API Using Postman

POST: https://localhost:5001/api/notification/send?user=Admin&message=Hello+SignalR

Response

{"Status": "Message Sent","User": "Admin","Message": "Hello SignalR"}

Your browser client will instantly show:

Admin: Hello SignalR

🌍 Advanced Use Cases

  • Authentication & Authorization: Restrict connections per user or group.

  • Groups: Send messages to specific user groups (Clients.Group("Admins")).

  • Connection Tracking: Handle OnConnectedAsync and OnDisconnectedAsync.

  • Scalability: Use Redis backplane for multi-server setups.

👉 Check official docs: Scaling SignalR with Redis

🧾 Summary

FeatureDescription
LibrarySignalR
PurposeReal-time bidirectional communication
Framework.NET Core Web API
ProtocolWebSockets (fallback to SSE/Long Polling)
Common UsesNotifications, chat, dashboards, live data

🏁 Conclusion

Integrating SignalR with your .NET Core API enables you to build modern, real-time applications with minimal effort. From chat systems to live monitoring dashboards, SignalR provides a fast, reliable, and scalable way to push data instantly to clients.

If you’re building APIs that require instant updates, SignalR should definitely be in your toolkit.

People also reading
Membership not found

AltStyle によって変換されたページ (->オリジナル) /