Skip to content

Websocket Configuration

Prerequisites

To use WebSockets in your application, you need to enable sessions. This requires adding the AddDistributedMemoryCache and AddSession services to your application configuration.

Program.cs
...
builder.Services
.AddDistributedMemoryCache()
.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30); // Set session timeout here
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
var app = builder.Build();
app
.UseSession()
.UseWebSockets(new WebSocketOptions()
{
KeepAliveInterval = TimeSpan.FromSeconds(120),
});
...

This setup allows the WebSocket to keep connections open for the lifecycle of the application. However, when the application stops, it’s possible for an open connection to remain active. To avoid this, you need to forcefully close all WebSocket connections when the application shuts down. You can achieve this by registering a stop action in Program.cs.

Program.cs
app.Lifetime.ApplicationStopping.Register(Aventus.Stop);

Then define the stop action :

Aventus.cs
public static class Aventus
{
// ...
public static void Stop()
{
// Forcefully close all WebSocket connections
WebSocketMiddleware.Stop().GetAwaiter().GetResult();
}
}

How to Configure WebSockets

To configure WebSocket handling in your application, use the following method within the Aventus class. This will set up WebSocket options and ensure your application correctly processes WebSocket requests.

Aventus.cs
private static void InitWs(VoidWithError initResult, WebApplication app)
{
WebSocketMiddleware.Configure((config) =>
{
// Set configuration properties here
// Example:
// config.PrintRoute = true;
});
// Register WebSocket routes
initResult.Run(WebSocketMiddleware.Register);
// Configure the app to use WebSocket handling
app.Use(WebSocketMiddleware.OnRequest);
}

Properties

transformPattern

  • Type: Func<string, Dictionary<string, WebSocketRouterParameterInfo>, object, bool, string>?
  • Description: A function that generates a string pattern to identify routes and events dynamically based on route parameters, method information, and other attributes. This can be used to create advanced routing patterns that adapt based on context.
    • string : the base path
    • Dictionary<string, WebSocketRouterParameterInfo> : Method parameters
    • object : IWsRouter or WsEvent
    • bool : Is it an event?

transformPatternIntoRegex

  • Type: Func<string, Regex>?
  • Description: A function that generates a string based on the transformPattern result

JSONSettings

  • Type: JsonSerializerSettings
  • Description: Configures JSON serialization settings for the router, including handling of null values, date formats, and custom converters. By default, it uses:
    • TypeNameHandling.Auto to include type metadata.
    • NullValueHandling.Ignore to omit null values in JSON.
    • DateFormatHandling.IsoDateFormat with the date format "yyyy-MM-ddTHH:mm:ss.fffZ" to ensure consistency.
    • A custom converter, AventusJsonConverter, for additional serialization control.

PrintRoute

  • Type: bool
  • Default: false
  • Description: If set to true, all routes will be listed in the console at application startup. Useful for debugging and verifying that all routes are correctly registered.

PrintTrigger

  • Type: bool
  • Default: false
  • Description: Enables logging of each route that is triggered, displaying them in the console when accessed. This can assist in tracking and debugging route usage in real-time.

This configuration provides a straightforward method for setting up websocket behavior in AventusSharp, with options to customize JSON handling, route logging, and more.