- ASP.NET Core-style WebSocket routing π£οΈ
- Method-based endpoint handlers (Like in ASP!) π―
- Simple integration with existing applications β‘
Add the NuGet package to your project:
dotnet add package yawaflua.WebSockets
public class ChatController : WebSocketController
{
[WebSocket("/chat")]
public override async Task OnMessageAsync(
IWebSocket webSocket,
HttpContext httpContext)
{
await webSocket.SendAsync("Message!");
}
}
public void ConfigureServices(IServiceCollection services)
{
services
.AddControllers()
.SettingUpWebSockets(); // β Add WebSocket routing
services.AddSingleton<ChatController>();
}
public void Configure(IApplicationBuilder app)
{
app.ConnectWebSockets(); // β Add WebSocket handling
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
public class NotificationsController : WebSocketController
{
[WebSocket("/notifications/{userId}")]
public override async Task OnMessageAsync(
IWebSocket webSocket,
HttpContext httpContext)
{
var userId = httpContext.Request.RouteValues["userId"];
// Handle user-specific notifications
}
}
[WebSocket("/game")]
public class GameController : WebSocketController
{
[WebSocket("join/{roomId}")]
public async Task JoinRoom(IWebSocket webSocket, HttpContext context)
{
// Handle room joining
}
[WebSocket("leave/{roomId}")]
public async Task LeaveRoom(IWebSocket webSocket, HttpContext context)
{
// Handle room leaving
}
}
[WebSocket("/chat")]
public class ChatController : WebSocketController
{
public static DbContext dbContext;
public ChatController(DbContext dbContext)
{
ChatController.dbContext = dbContext;
}
[WebSocket("join/{roomId}")]
public async Task JoinRoom(WebSocket webSocket, HttpContext context)
{
await dbContext.Add(...);
// Next your logic etc
}
[WebSocket("leave/{roomId}")]
public async Task LeaveRoom(WebSocket webSocket, HttpContext context)
{
// Handle room leaving
}
}
services.AddSingleton(new WebSocketConfig()
{
OnOpenHandler = async (socket, context) =>
{
if (socket.WebSocketManager!.GetAllClients().Count(k =>
Equals(k.ConnectionInfo!.RemoteIpAddress!.MapToIPv4(),
socket.Client.ConnectionInfo!.RemoteIpAddress!.MapToIPv4())) >= 3)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Too many users");
}
Console.WriteLine($"{socket.Client.Id} has been connected to {socket.Client.Path}");
}
})
- Connection - Automatically handled by middleware
- Message Handling - Implement
OnMessageAsync
- Cleanup - Dispose resources in
IDisposable
interface
- Keep Controllers Light - Move business logic to services
- Use Dependency Injection - Inject services via constructor
- Handle Exceptions - Wrap operations in try/catch blocks
- Manage State - Use
HttpContext.Items
for request-scoped data
No Route Handling?
- Verify controller registration in DI:
services.AddSingleton<YourController>();
Connection Issues?
- Ensure middleware order:
app.ConnectWebSockets(); // Must be before UseRouting/UseEndpoints
Parameters Not Working?
- Check route template syntax:
[WebSocket("/correct/{paramName}")] // β [WebSocket("/wrong/{param-name}")] // β