Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This article describes how to configure client and server options for ASP.NET Core SignalR.
For Blazor SignalR guidance, which adds to or supersedes the guidance in this article, see ASP.NET Core Blazor SignalR guidance.
Configure serialization for encoding messages
ASP.NET Core SignalR supports two protocols for encoding messages: JSON and MessagePack. Each protocol has serialization configuration options.
JSON serialization options
JSON serialization can be configured on the server by using the AddJsonProtocol extension method. AddJsonProtocol can be added after the AddSignalR method in Startup.ConfigureServices. The AddJsonProtocol method takes a delegate that receives an options object. The PayloadSerializerOptions property on that object is a System.Text.Json JsonSerializerOptions object that can be used to configure serialization of arguments and return values. For more information, see the System.Text.Json documentation.
For example, to configure the serializer to not change the casing of property names, rather than the default camel case names, use the following code in the Program.cs file:
builder.Services.AddSignalR()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
});
In the .NET client, the same AddJsonProtocol extension method exists on HubConnectionBuilder. The Microsoft.Extensions.DependencyInjection namespace must be imported to resolve the extension method:
// At the top of the file:
using Microsoft.Extensions.DependencyInjection;
// When constructing your connection:
var connection = new HubConnectionBuilder()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
})
.Build();
Note
It's not possible to configure JSON serialization in the JavaScript client at this time.
Switch to Newtonsoft.Json
If your app requires features in the Newtonsoft.Json package that aren't supported in System.Text.Json, see Switch to Newtonsoft.Json.
MessagePack serialization options
MessagePack serialization can be configured by providing a delegate to the AddMessagePackProtocol call. For more information, see MessagePack in SignalR.
Note
It's not possible to configure MessagePack serialization in the JavaScript client at this time.
Configure server options
The following table describes options for configuring SignalR hubs:
| Option | Default value | Description |
|---|---|---|
ClientTimeoutInterval |
30 seconds | The server considers the client disconnected if it doesn't receive a message (including keep-alive) within this interval. It can take longer than this timeout interval for the client to be marked disconnected due to how this feature is implemented. The recommended value is double the KeepAliveInterval value. |
HandshakeTimeout |
15 seconds | If the client doesn't send an initial handshake message within this time interval, the connection is closed. This option is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | The interval at which a ping message is automatically sent to keep the connection open. When you change the KeepAliveInterval value, change the ServerTimeout or serverTimeoutInMilliseconds setting on the client. The recommended ServerTimeout or serverTimeoutInMilliseconds value is double the KeepAliveInterval value. |
SupportedProtocols |
All installed protocols | Protocols supported by this hub. By default, all protocols registered on the server are allowed. Protocols can be removed from this list to disable specific protocols for individual hubs. |
EnableDetailedErrors |
false |
When this option is enabled (true), detailed exception messages are returned to clients when an exception is thrown in a hub method. The default is false because these exception messages can contain sensitive information. |
StreamBufferCapacity |
10 | The maximum number of items that can be buffered for client upload streams. When this limit is reached, the processing of invocations is blocked until the server processes stream items. |
MaximumReceiveMessageSize |
32 KB | The maximum size of a single incoming hub message. Increasing the value might increase the risk of Denial of service (DoS) attacks. |
MaximumParallelInvocationsPerClient |
1 | The maximum number of hub methods that each client can call in parallel before queueing. |
DisableImplicitFromServicesParameters |
false |
Hub method arguments are resolved from dependency injection, if possible. |
Options can be configured for all hubs by providing an options delegate to the AddSignalR call in the Program.cs file.
builder.Services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(1);
});
Options for a single hub override the global options provided in AddSignalR and can be configured by using the AddHubOptions method:
builder.Services.AddSignalR().AddHubOptions<ChatHub>(options =>
{
options.EnableDetailedErrors = true;
});
Configure advanced HTTP options
Use HttpConnectionDispatcherOptions to configure advanced settings related to transports and memory buffer management. These options are configured by passing a delegate to the MapHub method in Program.cs.
using Microsoft.AspNetCore.Http.Connections;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddSignalR();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.MapHub<ChatHub>("/chathub", options =>
{
options.Transports =
HttpTransportType.WebSockets |
HttpTransportType.LongPolling;
}
);
app.Run();
The following table describes options for configuring ASP.NET Core SignalR's advanced HTTP options:
| Option | Default value | Description |
|---|---|---|
ApplicationMaxBufferSize |
64 KB | The maximum number of bytes received from the client that the server buffers before applying backpressure. Increasing this value allows the server to receive larger messages faster without applying backpressure, but can increase memory consumption. |
TransportMaxBufferSize |
64 KB | The maximum number of bytes sent by the app that the server buffers before observing backpressure. Increasing this value allows the server to buffer larger messages faster without awaiting backpressure, but can increase memory consumption. |
AuthorizationData |
Data automatically gathered from the Authorize attributes applied to the Hub class. |
A list of IAuthorizeData objects used to determine if a client is authorized to connect to the hub. |
Transports |
All Transports are enabled. | A bit flags enum of HttpTransportType values that can restrict the transports a client can use to connect. |
LongPolling |
See Configure Long Polling transport | Options specific to the Long Polling transport. |
WebSockets |
See Configure WebSocket transport | Options specific to the WebSockets transport. |
MinimumProtocolVersion |
0 | The minimum version of the negotiation protocol. This value is used to limit clients to newer versions of the protocol. |
CloseOnAuthenticationExpiration |
false |
Controls authentication expiration tracking, which closes connections when a token expires. |
Configure Long Polling transport
The Long Polling transport has other options that can be configured by using the LongPolling property:
| Option | Default value | Description |
|---|---|---|
PollTimeout |
90 seconds | The maximum amount of time the server waits for a message to send to the client before terminating a single poll request. Decreasing this value causes the client to issue new poll requests more frequently. |
Configure WebSocket transport
The WebSocket transport has other options that can be configured by using the WebSockets property:
| Option | Default value | Description |
|---|---|---|
CloseTimeout |
5 seconds | After the server closes, if the client fails to close within this time interval, the connection is terminated. |
SubProtocolSelector |
null |
A delegate that can be used to set the Sec-WebSocket-Protocol header to a custom value. The delegate receives the values requested by the client as input and is expected to return the desired value. |
Configure client options
In the .NET client and JavaScript client, the client options are configured on the HubConnectionBuilder type. In the Java client, the options are configured on the HttpHubConnectionBuilder subclass, which contains the builder configuration options and the HubConnection itself.
Configure logging
Logging is configured in the .NET client by using the ConfigureLogging method. Logging providers and filters can be registered in the same way as they are on the server. For more information, see the Logging in ASP.NET Core documentation.
Note
To register logging providers, you must install the necessary packages. For more information, see the full list of Built-in logging providers.
For example, to enable Console logging, install the Microsoft.Extensions.Logging.Console NuGet package. Call the AddConsole extension method:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub")
.ConfigureLogging(logging => {
logging.SetMinimumLevel(LogLevel.Information);
logging.AddConsole();
})
.Build();
In the JavaScript client, a similar configureLogging method exists. Provide a LogLevel value as the minimum level of log messages to produce. Logs are written to the browser console window.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging(signalR.LogLevel.Information)
.build();
Instead of a LogLevel value, you can also provide a string value that represents a log level name. This approach is useful when configuring SignalR logging in environments where you don't have access to the LogLevel constants.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging("warn")
.build();
The following table lists the available log levels. The value you provide to configureLogging sets the minimum log level for logging. Messages logged at this level, or the levels listed after it in the table, are logged.
| String | LogLevel |
|---|---|
trace |
LogLevel.Trace |
debug |
LogLevel.Debug |
info or information |
LogLevel.Information |
warn or warning |
LogLevel.Warning |
error |
LogLevel.Error |
critical |
LogLevel.Critical |
none |
LogLevel.None |
Note
To disable logging entirely, specify signalR.LogLevel.None in the configureLogging method.
For more information on logging, see Logging and diagnostics in ASP.NET Core SignalR.
The SignalR Java client uses the Simple Logging Facade for Java (SLF4J) library for logging. It's a high-level logging API that allows users of the library to choose their own specific logging implementation by bringing in a specific logging dependency. The following code snippet shows how to use java.util.logging with the SignalR Java client.
implementation 'org.slf4j:slf4j-jdk14:1.7.25'
If you don't configure logging in your dependencies, SLF4J loads a default no-operation logger with the following warning message:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
You can safely ignore this message.
Configure allowed transports
The transports used by SignalR can be configured in the WithUrl call (withUrl in JavaScript). A bitwise-OR of the values of HttpTransportType can be used to restrict the client to only use the specified transports. All transports are enabled by default.
For example, to disable the Server-Sent Events transport, but allow WebSockets and Long Polling connections:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", HttpTransportType.WebSockets | HttpTransportType.LongPolling)
.Build();
In the JavaScript client, transports are configured by setting the transport field on the options object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", { transport: signalR.HttpTransportType.WebSockets | signalR.HttpTransportType.LongPolling })
.build();
In this version of the Java client, WebSockets is the only available transport.
In the Java client, the transport is selected by using the withTransport method on the HttpHubConnectionBuilder. The Java client defaults to using the WebSockets transport.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withTransport(TransportEnum.WEBSOCKETS)
.build();
Note
The SignalR Java client doesn't currently support transport fallback.
Configure bearer authentication
To provide authentication data along with SignalR requests, use the AccessTokenProvider option (accessTokenFactory in JavaScript) to specify a function that returns the desired access token. In the .NET client, this access token is passed in as an HTTP "Bearer Authentication" token (using the Authorization header with a type of Bearer). In the JavaScript client, the access token is used as a Bearer token, except in a few cases where browser APIs restrict the ability to apply headers (specifically, in Server-Sent Events and WebSockets requests). In these cases, the access token is provided as a query string value access_token.
In the .NET client, the AccessTokenProvider option can be specified by using the options delegate in WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.AccessTokenProvider = async () => {
// Get and return the access token.
};
})
.Build();
In the JavaScript client, the access token is configured by setting the accessTokenFactory field on the options object in withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
accessTokenFactory: () => {
// Get and return the access token.
// This function can return a JavaScript Promise if asynchronous
// logic is required to retrieve the access token.
}
})
.build();
In the SignalR Java client, you can configure a bearer token to use for authentication by supplying an access token provider to the HttpHubConnectionBuilder. Use withAccessTokenProvider to provide an RxJava Single<String>. With a call to Single.defer, you can write logic to produce access tokens for your client.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withAccessTokenProvider(Single.defer(() -> {
// Your logic here.
return Single.just("An Access Token");
})).build();
Configure timeout and keep-alive options
This section describes other options for configuring timeout and keep-alive behavior.
| Option | Default value | Description |
|---|---|---|
WithServerTimeout |
30 seconds (30,000 milliseconds) | The timeout value for server activity, which is set directly on the HubConnectionBuilder. If the server doesn't send a message within this interval, the client considers the server disconnected and triggers the Closed event (onclose in JavaScript). This value must be large enough for a ping message to be sent from the server and received by the client within the timeout interval. The recommended value is a number at least double the server's keep-alive interval (WithKeepAliveInterval) value to allow time for pings to arrive. |
HandshakeTimeout |
15 seconds | The timeout value for the initial server handshake, which is available on the HubConnection object itself. If the server doesn't send a handshake response within this interval, the client cancels the handshake and triggers the Closed event (onclose in JavaScript). This option is an advanced setting that should be modified only if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
WithKeepAliveInterval |
15 seconds | This value determines the interval at which the client sends ping messages and is set directly on the HubConnectionBuilder. This setting allows the server to detect hard disconnects, such as when a client unplugs their computer from the network. Sending any message from the client resets the timer to the start of the interval. If the client doesn't send a message within the ClientTimeoutInterval set on the server, the server considers the client disconnected. |
In the .NET client, timeout values are specified as TimeSpan values.
The following example shows values that are double the default values:
var builder = new HubConnectionBuilder()
.WithUrl(Navigation.ToAbsoluteUri("/chathub"))
.WithServerTimeout(TimeSpan.FromSeconds(60))
.WithKeepAliveInterval(TimeSpan.FromSeconds(30))
.Build();
builder.On<string, string>("ReceiveMessage", (user, message) => ...
await builder.StartAsync();
Configure stateful reconnect
SignalR stateful reconnect reduces the perceived downtime of clients that have a temporary disconnect in their network connection, such as when switching network connections or a short temporary loss in access.
Stateful reconnect achieves the perceived downtime by:
- Temporarily buffering data on the server and client.
- Acknowledging messages received (ACK-ing) by both the server and client.
- Recognizing when a connection is up and replaying messages that might be sent while the connection is down.
Stateful reconnect is available in .NET 8 or later.
Enable stateful reconnect
You can opt in to stateful reconnect at both the server hub endpoint and the client.
On the server hub endpoint, update the configuration to enable the
AllowStatefulReconnectsoption:app.MapHub<MyHub>("/hubName", options => { options.AllowStatefulReconnects = true; });Optionally, the maximum buffer size in bytes allowed by the server can be set globally or for a specific hub with the
StatefulReconnectBufferSizeoption.Set the
StatefulReconnectBufferSizeoption globally:builder.AddSignalR(o => o.StatefulReconnectBufferSize = 1000);Set the
StatefulReconnectBufferSizeoption for a specific hub:builder.AddSignalR().AddHubOptions<MyHub>(o => o.StatefulReconnectBufferSize = 1000);
The
StatefulReconnectBufferSizesetting is optional with a default size of 100,000 bytes.On the client, update the JavaScript or TypeScript code to enable the
withStatefulReconnectoption:const builder = new signalR.HubConnectionBuilder() .withUrl("/hubname") .withStatefulReconnect({ bufferSize: 1000 }); // Optional, defaults to 100,000 const connection = builder.build();The
bufferSizesetting is optional with a default size of 100,000 bytes.On the .NET client, update the code to enable the
WithStatefulReconnectoption:var builder = new HubConnectionBuilder() .WithUrl("<hub url>") .WithStatefulReconnect(); builder.Services.Configure<HubConnectionOptions>(o => o.StatefulReconnectBufferSize = 1000); var hubConnection = builder.Build();The
StatefulReconnectBufferSizesetting is optional with a default size of 100,000 bytes.
Configure other options
You can configure other options in the WithUrl (withUrl in JavaScript) method on HubConnectionBuilder or on the various configuration APIs on the HttpHubConnectionBuilder in the Java client.
| Option | Default value | Description |
|---|---|---|
AccessTokenProvider |
null |
A function that returns a string, which is provided as a Bearer authentication token in HTTP requests. |
SkipNegotiation |
false |
Set this option to true to skip the negotiation step. Note: This option is available only when the WebSockets transport is the only enabled transport. The setting can't be enabled when using the Azure SignalR Service. |
ClientCertificates |
Empty | A collection of Transport Layer Security (TLS) certificates to send to authenticate requests. |
Cookies |
Empty | A collection of HTTP cookies to send with every HTTP request. |
Credentials |
Empty | The credentials to send with every HTTP request. |
CloseTimeout |
5 seconds | The maximum amount of time the client waits after closing for the server to acknowledge the close request. If the server doesn't acknowledge the close within this time, the client disconnects. Note: This setting is available for WebSockets only. |
Headers |
Empty | A map of other HTTP headers to send with every HTTP request. |
HttpMessageHandlerFactory |
null |
A delegate that can be used to configure or replace the HttpMessageHandler used to send HTTP requests. This delegate must return a non-null value, and it receives the default value as a parameter. You can either modify settings on that default value and return it, or return a new HttpMessageHandler instance. Note: - When you replace the handler, be sure to copy the settings you want to keep from the provided handler. Otherwise, the configured options (such as Cookies and Headers) don't apply to the new handler. - This setting isn't used for WebSocket connections. |
Proxy |
null |
An HTTP proxy to use when sending HTTP requests. |
UseDefaultCredentials |
false |
Set this boolean to send the default credentials for HTTP and WebSockets requests. This option enables the use of Windows authentication. |
WebSocketConfiguration |
null |
A delegate that can be used to configure more WebSocket options. Receives an instance of ClientWebSocketOptions that can be used to configure the options. |
ApplicationMaxBufferSize |
1 MB | The maximum number of bytes received from the server that the client buffers before applying backpressure. Increasing this value allows the client to receive larger messages faster without applying backpressure, but can increase memory consumption. |
TransportMaxBufferSize |
1 MB | The maximum number of bytes sent by the user application that the client buffers before observing backpressure. Increasing this value allows the client to buffer larger messages faster without awaiting backpressure, but can increase memory consumption. |
In the .NET client, these options can be modified in the options delegate provided to WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.Headers["Foo"] = "Bar";
options.SkipNegotiation = true;
options.Transports = HttpTransportType.WebSockets;
options.Cookies.Add(new Cookie(/* ... */);
options.ClientCertificates.Add(/* ... */);
})
.Build();
Related content
JSON/MessagePack serialization options
ASP.NET Core SignalR supports two protocols for encoding messages: JSON and MessagePack. Each protocol has serialization configuration options.
JSON serialization can be configured on the server using the AddJsonProtocol extension method, which can be added after AddSignalR in your Startup.ConfigureServices method. The AddJsonProtocol method takes a delegate that receives an options object. The PayloadSerializerSettings property on that object is a Json.NET JsonSerializerSettings object that can be used to configure serialization of arguments and return values. For more information, see the Json.NET documentation.
For example, to configure the serializer to use "PascalCase" property names, rather than the default camel case names, use the following code in Startup.ConfigureServices:
services.AddSignalR()
.AddJsonProtocol(options => {
options.PayloadSerializerSettings.ContractResolver =
new DefaultContractResolver();
});
In the .NET client, the same AddJsonProtocol extension method exists on HubConnectionBuilder. The Microsoft.Extensions.DependencyInjection namespace must be imported to resolve the extension method:
// At the top of the file:
using Microsoft.Extensions.DependencyInjection;
// When constructing your connection:
var connection = new HubConnectionBuilder()
.AddJsonProtocol(options => {
options.PayloadSerializerSettings.ContractResolver =
new DefaultContractResolver();
})
.Build();
Note
It's not possible to configure JSON serialization in the JavaScript client at this time.
MessagePack serialization options
MessagePack serialization can be configured by providing a delegate to the AddMessagePackProtocol call. See MessagePack in SignalR for more details.
Note
It's not possible to configure MessagePack serialization in the JavaScript client at this time.
Configure server options
The following table describes options for configuring SignalR hubs:
| Option | Default Value | Description |
|---|---|---|
HandshakeTimeout |
15 seconds | If the client doesn't send an initial handshake message within this time interval, the connection is closed. This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | If the server hasn't sent a message within this interval, a ping message is sent automatically to keep the connection open. When changing KeepAliveInterval, change the ServerTimeout or serverTimeoutInMilliseconds setting on the client. The recommended ServerTimeout or serverTimeoutInMilliseconds value is double the KeepAliveInterval value. |
SupportedProtocols |
All installed protocols | Protocols supported by this hub. By default, all protocols registered on the server are allowed. Protocols can be removed from this list to disable specific protocols for individual hubs. |
EnableDetailedErrors |
false |
If true, detailed exception messages are returned to clients when an exception is thrown in a Hub method. The default is false because these exception messages can contain sensitive information. |
Options can be configured for all hubs by providing an options delegate to the AddSignalR call in Startup.ConfigureServices.
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(1);
});
}
Options for a single hub override the global options provided in AddSignalR and can be configured using AddHubOptions:
services.AddSignalR().AddHubOptions<ChatHub>(options =>
{
options.EnableDetailedErrors = true;
});
Advanced HTTP configuration options
Use HttpConnectionDispatcherOptions to configure advanced settings related to transports and memory buffer management. These options are configured by passing a delegate to MapHub in Startup.Configure.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSignalR((configure) =>
{
var desiredTransports =
HttpTransportType.WebSockets |
HttpTransportType.LongPolling;
configure.MapHub<ChatHub>("/chathub", (options) =>
{
options.Transports = desiredTransports;
});
});
}
The following table describes options for configuring ASP.NET Core SignalR's advanced HTTP options:
| Option | Default Value | Description |
|---|---|---|
ApplicationMaxBufferSize |
32 KB | The maximum number of bytes received from the client that the server buffers. Increasing this value allows the server to receive larger messages, but can negatively impact memory consumption. |
AuthorizationData |
Data automatically gathered from the Authorize attributes applied to the Hub class. |
A list of IAuthorizeData objects used to determine if a client is authorized to connect to the hub. |
TransportMaxBufferSize |
32 KB | The maximum number of bytes sent by the app that the server buffers. Increasing this value allows the server to send larger messages, but can negatively impact memory consumption. |
Transports |
All Transports are enabled. | A bit flags enum of HttpTransportType values that can restrict the transports a client can use to connect. |
LongPolling |
See below. | Additional options specific to the Long Polling transport. |
WebSockets |
See below. | Additional options specific to the WebSockets transport. |
The Long Polling transport has additional options that can be configured using the LongPolling property:
| Option | Default Value | Description |
|---|---|---|
PollTimeout |
90 seconds | The maximum amount of time the server waits for a message to send to the client before terminating a single poll request. Decreasing this value causes the client to issue new poll requests more frequently. |
The WebSocket transport has additional options that can be configured using the WebSockets property:
| Option | Default Value | Description |
|---|---|---|
CloseTimeout |
5 seconds | After the server closes, if the client fails to close within this time interval, the connection is terminated. |
SubProtocolSelector |
null |
A delegate that can be used to set the Sec-WebSocket-Protocol header to a custom value. The delegate receives the values requested by the client as input and is expected to return the desired value. |
Configure client options
Client options can be configured on the HubConnectionBuilder type (available in the .NET and JavaScript clients). It's also available in the Java client, but the HttpHubConnectionBuilder subclass is what contains the builder configuration options, as well as on the HubConnection itself.
Configure logging
Logging is configured in the .NET Client using the ConfigureLogging method. Logging providers and filters can be registered in the same way as they are on the server. See the Logging in ASP.NET Core documentation for more information.
Note
In order to register Logging providers, you must install the necessary packages. See the Built-in logging providers section of the docs for a full list.
For example, to enable Console logging, install the Microsoft.Extensions.Logging.Console NuGet package. Call the AddConsole extension method:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub")
.ConfigureLogging(logging => {
logging.SetMinimumLevel(LogLevel.Information);
logging.AddConsole();
})
.Build();
In the JavaScript client, a similar configureLogging method exists. Provide a LogLevel value indicating the minimum level of log messages to produce. Logs are written to the browser console window.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging(signalR.LogLevel.Information)
.build();
Note
To disable logging entirely, specify signalR.LogLevel.None in the configureLogging method.
For more information on logging, see the SignalR Diagnostics documentation.
The SignalR Java client uses the SLF4J library for logging. It's a high-level logging API that allows users of the library to choose their own specific logging implementation by bringing in a specific logging dependency. The following code snippet shows how to use java.util.logging with the SignalR Java client.
implementation 'org.slf4j:slf4j-jdk14:1.7.25'
If you don't configure logging in your dependencies, SLF4J loads a default no-operation logger with the following warning message:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
This can safely be ignored.
Configure allowed transports
The transports used by SignalR can be configured in the WithUrl call (withUrl in JavaScript). A bitwise-OR of the values of HttpTransportType can be used to restrict the client to only use the specified transports. All transports are enabled by default.
For example, to disable the Server-Sent Events transport, but allow WebSockets and Long Polling connections:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", HttpTransportType.WebSockets | HttpTransportType.LongPolling)
.Build();
In the JavaScript client, transports are configured by setting the transport field on the options object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", { transport: signalR.HttpTransportType.WebSockets | signalR.HttpTransportType.LongPolling })
.build();
Configure bearer authentication
To provide authentication data along with SignalR requests, use the AccessTokenProvider option (accessTokenFactory in JavaScript) to specify a function that returns the desired access token. In the .NET Client, this access token is passed in as an HTTP "Bearer Authentication" token (Using the Authorization header with a type of Bearer). In the JavaScript client, the access token is used as a Bearer token, except in a few cases where browser APIs restrict the ability to apply headers (specifically, in Server-Sent Events and WebSockets requests). In these cases, the access token is provided as a query string value access_token.
In the .NET client, the AccessTokenProvider option can be specified using the options delegate in WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.AccessTokenProvider = async () => {
// Get and return the access token.
};
})
.Build();
In the JavaScript client, the access token is configured by setting the accessTokenFactory field on the options object in withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
accessTokenFactory: () => {
// Get and return the access token.
// This function can return a JavaScript Promise if asynchronous
// logic is required to retrieve the access token.
}
})
.build();
In the SignalR Java client, you can configure a bearer token to use for authentication by providing an access token factory to the HttpHubConnectionBuilder. Use withAccessTokenFactory to provide an RxJava Single<String>. With a call to Single.defer, you can write logic to produce access tokens for your client.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withAccessTokenProvider(Single.defer(() -> {
// Your logic here.
return Single.just("An Access Token");
})).build();
Configure timeout and keep-alive options
Additional options for configuring timeout and keep-alive behavior are available on the HubConnection object itself:
| Option | Default value | Description |
|---|---|---|
ServerTimeout |
30 seconds (30,000 milliseconds) | Timeout for server activity. If the server hasn't sent a message in this interval, the client considers the server disconnected and triggers the Closed event (onclose in JavaScript). This value must be large enough for a ping message to be sent from the server and received by the client within the timeout interval. The recommended value is a number at least double the server's KeepAliveInterval value to allow time for pings to arrive. |
HandshakeTimeout |
15 seconds | Timeout for initial server handshake. If the server doesn't send a handshake response in this interval, the client cancels the handshake and triggers the Closed event (onclose in JavaScript). This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
In the .NET Client, timeout values are specified as TimeSpan values.
Configure additional options
Additional options can be configured in the WithUrl (withUrl in JavaScript) method on HubConnectionBuilder or on the various configuration APIs on the HttpHubConnectionBuilder in the Java client:
| .NET Option | Default value | Description |
|---|---|---|
AccessTokenProvider |
null |
A function returning a string that is provided as a Bearer authentication token in HTTP requests. |
SkipNegotiation |
false |
Set this to true to skip the negotiation step. Only supported when the WebSockets transport is the only enabled transport. This setting can't be enabled when using the Azure SignalR Service. |
ClientCertificates |
Empty | A collection of TLS certificates to send to authenticate requests. |
Cookies |
Empty | A collection of HTTP cookies to send with every HTTP request. |
Credentials |
Empty | Credentials to send with every HTTP request. |
CloseTimeout |
5 seconds | WebSockets only. The maximum amount of time the client waits after closing for the server to acknowledge the close request. If the server doesn't acknowledge the close within this time, the client disconnects. |
Headers |
Empty | A Map of additional HTTP headers to send with every HTTP request. |
HttpMessageHandlerFactory |
null |
A delegate that can be used to configure or replace the HttpMessageHandler used to send HTTP requests. Not used for WebSocket connections. This delegate must return a non-null value, and it receives the default value as a parameter. Either modify settings on that default value and return it, or return a new HttpMessageHandler instance. When replacing the handler make sure to copy the settings you want to keep from the provided handler, otherwise, the configured options (such as Cookies and Headers) won't apply to the new handler. |
Proxy |
null |
An HTTP proxy to use when sending HTTP requests. |
UseDefaultCredentials |
false |
Set this boolean to send the default credentials for HTTP and WebSockets requests. This enables the use of Windows authentication. |
WebSocketConfiguration |
null |
A delegate that can be used to configure additional WebSocket options. Receives an instance of ClientWebSocketOptions that can be used to configure the options. |
In the .NET Client, these options can be modified by the options delegate provided to WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.Headers["Foo"] = "Bar";
options.Cookies.Add(new Cookie(/* ... */);
options.ClientCertificates.Add(/* ... */);
})
.Build();
In the JavaScript Client, these options can be provided in a JavaScript object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.build();
In the Java client, these options can be configured with the methods on the HttpHubConnectionBuilder returned from the HubConnectionBuilder.create("HUB URL")
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withHeader("Foo", "Bar")
.shouldSkipNegotiate(true)
.withHandshakeResponseTimeout(30*1000)
.build();
Additional resources
JSON/MessagePack serialization options
ASP.NET Core SignalR supports two protocols for encoding messages: JSON and MessagePack. Each protocol has serialization configuration options.
JSON serialization can be configured on the server using the AddJsonProtocol extension method, which can be added after AddSignalR in your Startup.ConfigureServices method. The AddJsonProtocol method takes a delegate that receives an options object. The PayloadSerializerSettings property on that object is a Json.NET JsonSerializerSettings object that can be used to configure serialization of arguments and return values. For more information, see the Json.NET documentation.
For example, to configure the serializer to use "PascalCase" property names, rather than the default camel case names, use the following code in Startup.ConfigureServices:
services.AddSignalR()
.AddJsonProtocol(options => {
options.PayloadSerializerSettings.ContractResolver =
new DefaultContractResolver();
});
In the .NET client, the same AddJsonProtocol extension method exists on HubConnectionBuilder. The Microsoft.Extensions.DependencyInjection namespace must be imported to resolve the extension method:
// At the top of the file:
using Microsoft.Extensions.DependencyInjection;
// When constructing your connection:
var connection = new HubConnectionBuilder()
.AddJsonProtocol(options => {
options.PayloadSerializerSettings.ContractResolver =
new DefaultContractResolver();
})
.Build();
Note
It's not possible to configure JSON serialization in the JavaScript client at this time.
MessagePack serialization options
MessagePack serialization can be configured by providing a delegate to the AddMessagePackProtocol call. See MessagePack in SignalR for more details.
Note
It's not possible to configure MessagePack serialization in the JavaScript client at this time.
Configure server options
The following table describes options for configuring SignalR hubs:
| Option | Default Value | Description |
|---|---|---|
ClientTimeoutInterval |
30 seconds | The server considers the client disconnected if it hasn't received a message (including keep-alive) in this interval. It could take longer than this timeout interval for the client to be marked disconnected due to how this is implemented. The recommended value is double the KeepAliveInterval value. |
HandshakeTimeout |
15 seconds | If the client doesn't send an initial handshake message within this time interval, the connection is closed. This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | If the server hasn't sent a message within this interval, a ping message is sent automatically to keep the connection open. When changing KeepAliveInterval, change the ServerTimeout or serverTimeoutInMilliseconds setting on the client. The recommended ServerTimeout or serverTimeoutInMilliseconds value is double the KeepAliveInterval value. |
SupportedProtocols |
All installed protocols | Protocols supported by this hub. By default, all protocols registered on the server are allowed. Protocols can be removed from this list to disable specific protocols for individual hubs. |
EnableDetailedErrors |
false |
If true, detailed exception messages are returned to clients when an exception is thrown in a Hub method. The default is false because these exception messages can contain sensitive information. |
Options can be configured for all hubs by providing an options delegate to the AddSignalR call in Startup.ConfigureServices.
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(1);
});
}
Options for a single hub override the global options provided in AddSignalR and can be configured using AddHubOptions:
services.AddSignalR().AddHubOptions<ChatHub>(options =>
{
options.EnableDetailedErrors = true;
});
Advanced HTTP configuration options
Use HttpConnectionDispatcherOptions to configure advanced settings related to transports and memory buffer management. These options are configured by passing a delegate to MapHub in Startup.Configure.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSignalR((configure) =>
{
var desiredTransports =
HttpTransportType.WebSockets |
HttpTransportType.LongPolling;
configure.MapHub<ChatHub>("/chathub", (options) =>
{
options.Transports = desiredTransports;
});
});
}
The following table describes options for configuring ASP.NET Core SignalR's advanced HTTP options:
| Option | Default Value | Description |
|---|---|---|
ApplicationMaxBufferSize |
32 KB | The maximum number of bytes received from the client that the server buffers. Increasing this value allows the server to receive larger messages, but can negatively impact memory consumption. |
AuthorizationData |
Data automatically gathered from the Authorize attributes applied to the Hub class. |
A list of IAuthorizeData objects used to determine if a client is authorized to connect to the hub. |
TransportMaxBufferSize |
32 KB | The maximum number of bytes sent by the app that the server buffers. Increasing this value allows the server to send larger messages, but can negatively impact memory consumption. |
Transports |
All Transports are enabled. | A bit flags enum of HttpTransportType values that can restrict the transports a client can use to connect. |
LongPolling |
See below. | Additional options specific to the Long Polling transport. |
WebSockets |
See below. | Additional options specific to the WebSockets transport. |
The Long Polling transport has additional options that can be configured using the LongPolling property:
| Option | Default Value | Description |
|---|---|---|
PollTimeout |
90 seconds | The maximum amount of time the server waits for a message to send to the client before terminating a single poll request. Decreasing this value causes the client to issue new poll requests more frequently. |
The WebSocket transport has additional options that can be configured using the WebSockets property:
| Option | Default Value | Description |
|---|---|---|
CloseTimeout |
5 seconds | After the server closes, if the client fails to close within this time interval, the connection is terminated. |
SubProtocolSelector |
null |
A delegate that can be used to set the Sec-WebSocket-Protocol header to a custom value. The delegate receives the values requested by the client as input and is expected to return the desired value. |
Configure client options
Client options can be configured on the HubConnectionBuilder type (available in the .NET and JavaScript clients). It's also available in the Java client, but the HttpHubConnectionBuilder subclass is what contains the builder configuration options, as well as on the HubConnection itself.
Configure logging
Logging is configured in the .NET Client using the ConfigureLogging method. Logging providers and filters can be registered in the same way as they are on the server. See the Logging in ASP.NET Core documentation for more information.
Note
In order to register Logging providers, you must install the necessary packages. See the Built-in logging providers section of the docs for a full list.
For example, to enable Console logging, install the Microsoft.Extensions.Logging.Console NuGet package. Call the AddConsole extension method:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub")
.ConfigureLogging(logging => {
logging.SetMinimumLevel(LogLevel.Information);
logging.AddConsole();
})
.Build();
In the JavaScript client, a similar configureLogging method exists. Provide a LogLevel value indicating the minimum level of log messages to produce. Logs are written to the browser console window.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging(signalR.LogLevel.Information)
.build();
Note
To disable logging entirely, specify signalR.LogLevel.None in the configureLogging method.
For more information on logging, see the SignalR Diagnostics documentation.
The SignalR Java client uses the SLF4J library for logging. It's a high-level logging API that allows users of the library to choose their own specific logging implementation by bringing in a specific logging dependency. The following code snippet shows how to use java.util.logging with the SignalR Java client.
implementation 'org.slf4j:slf4j-jdk14:1.7.25'
If you don't configure logging in your dependencies, SLF4J loads a default no-operation logger with the following warning message:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
This can safely be ignored.
Configure allowed transports
The transports used by SignalR can be configured in the WithUrl call (withUrl in JavaScript). A bitwise-OR of the values of HttpTransportType can be used to restrict the client to only use the specified transports. All transports are enabled by default.
For example, to disable the Server-Sent Events transport, but allow WebSockets and Long Polling connections:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", HttpTransportType.WebSockets | HttpTransportType.LongPolling)
.Build();
In the JavaScript client, transports are configured by setting the transport field on the options object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", { transport: signalR.HttpTransportType.WebSockets | signalR.HttpTransportType.LongPolling })
.build();
In this version of the Java client WebSockets is the only available transport.
Configure bearer authentication
To provide authentication data along with SignalR requests, use the AccessTokenProvider option (accessTokenFactory in JavaScript) to specify a function that returns the desired access token. In the .NET Client, this access token is passed in as an HTTP "Bearer Authentication" token (Using the Authorization header with a type of Bearer). In the JavaScript client, the access token is used as a Bearer token, except in a few cases where browser APIs restrict the ability to apply headers (specifically, in Server-Sent Events and WebSockets requests). In these cases, the access token is provided as a query string value access_token.
In the .NET client, the AccessTokenProvider option can be specified using the options delegate in WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.AccessTokenProvider = async () => {
// Get and return the access token.
};
})
.Build();
In the JavaScript client, the access token is configured by setting the accessTokenFactory field on the options object in withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
accessTokenFactory: () => {
// Get and return the access token.
// This function can return a JavaScript Promise if asynchronous
// logic is required to retrieve the access token.
}
})
.build();
In the SignalR Java client, you can configure a bearer token to use for authentication by providing an access token factory to the HttpHubConnectionBuilder. Use withAccessTokenFactory to provide an RxJava Single<String>. With a call to Single.defer, you can write logic to produce access tokens for your client.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withAccessTokenProvider(Single.defer(() -> {
// Your logic here.
return Single.just("An Access Token");
})).build();
Configure timeout and keep-alive options
Additional options for configuring timeout and keep-alive behavior are available on the HubConnection object itself:
| Option | Default value | Description |
|---|---|---|
ServerTimeout |
30 seconds (30,000 milliseconds) | Timeout for server activity. If the server hasn't sent a message in this interval, the client considers the server disconnected and triggers the Closed event (onclose in JavaScript). This value must be large enough for a ping message to be sent from the server and received by the client within the timeout interval. The recommended value is a number at least double the server's KeepAliveInterval value to allow time for pings to arrive. |
HandshakeTimeout |
15 seconds | Timeout for initial server handshake. If the server doesn't send a handshake response in this interval, the client cancels the handshake and triggers the Closed event (onclose in JavaScript). This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | Determines the interval at which the client sends ping messages. Sending any message from the client resets the timer to the start of the interval. If the client hasn't sent a message in the ClientTimeoutInterval set on the server, the server considers the client disconnected. |
In the .NET Client, timeout values are specified as TimeSpan values.
Configure additional options
Additional options can be configured in the WithUrl (withUrl in JavaScript) method on HubConnectionBuilder or on the various configuration APIs on the HttpHubConnectionBuilder in the Java client:
| .NET Option | Default value | Description |
|---|---|---|
AccessTokenProvider |
null |
A function returning a string that is provided as a Bearer authentication token in HTTP requests. |
SkipNegotiation |
false |
Set this to true to skip the negotiation step. Only supported when the WebSockets transport is the only enabled transport. This setting can't be enabled when using the Azure SignalR Service. |
ClientCertificates |
Empty | A collection of TLS certificates to send to authenticate requests. |
Cookies |
Empty | A collection of HTTP cookies to send with every HTTP request. |
Credentials |
Empty | Credentials to send with every HTTP request. |
CloseTimeout |
5 seconds | WebSockets only. The maximum amount of time the client waits after closing for the server to acknowledge the close request. If the server doesn't acknowledge the close within this time, the client disconnects. |
Headers |
Empty | A Map of additional HTTP headers to send with every HTTP request. |
HttpMessageHandlerFactory |
null |
A delegate that can be used to configure or replace the HttpMessageHandler used to send HTTP requests. Not used for WebSocket connections. This delegate must return a non-null value, and it receives the default value as a parameter. Either modify settings on that default value and return it, or return a new HttpMessageHandler instance. When replacing the handler make sure to copy the settings you want to keep from the provided handler, otherwise, the configured options (such as Cookies and Headers) won't apply to the new handler. |
Proxy |
null |
An HTTP proxy to use when sending HTTP requests. |
UseDefaultCredentials |
false |
Set this boolean to send the default credentials for HTTP and WebSockets requests. This enables the use of Windows authentication. |
WebSocketConfiguration |
null |
A delegate that can be used to configure additional WebSocket options. Receives an instance of ClientWebSocketOptions that can be used to configure the options. |
In the .NET Client, these options can be modified by the options delegate provided to WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.Headers["Foo"] = "Bar";
options.Cookies.Add(new Cookie(/* ... */);
options.ClientCertificates.Add(/* ... */);
})
.Build();
In the JavaScript Client, these options can be provided in a JavaScript object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.build();
In the Java client, these options can be configured with the methods on the HttpHubConnectionBuilder returned from the HubConnectionBuilder.create("HUB URL")
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withHeader("Foo", "Bar")
.shouldSkipNegotiate(true)
.withHandshakeResponseTimeout(30*1000)
.build();
Additional resources
JSON/MessagePack serialization options
ASP.NET Core SignalR supports two protocols for encoding messages: JSON and MessagePack. Each protocol has serialization configuration options.
JSON serialization can be configured on the server using the AddJsonProtocol extension method. AddJsonProtocol can be added after AddSignalR in Startup.ConfigureServices. The AddJsonProtocol method takes a delegate that receives an options object. The PayloadSerializerOptions property on that object is a System.Text.Json JsonSerializerOptions object that can be used to configure serialization of arguments and return values. For more information, see the System.Text.Json documentation.
For example, to configure the serializer to not change the casing of property names, rather than the default camel case names, use the following code in Startup.ConfigureServices:
services.AddSignalR()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
});
In the .NET client, the same AddJsonProtocol extension method exists on HubConnectionBuilder. The Microsoft.Extensions.DependencyInjection namespace must be imported to resolve the extension method:
// At the top of the file:
using Microsoft.Extensions.DependencyInjection;
// When constructing your connection:
var connection = new HubConnectionBuilder()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
})
.Build();
Note
It's not possible to configure JSON serialization in the JavaScript client at this time.
Switch to Newtonsoft.Json
If you need features of Newtonsoft.Json that aren't supported in System.Text.Json, see Switch to Newtonsoft.Json.
MessagePack serialization options
MessagePack serialization can be configured by providing a delegate to the AddMessagePackProtocol call. See MessagePack in SignalR for more details.
Note
It's not possible to configure MessagePack serialization in the JavaScript client at this time.
Configure server options
The following table describes options for configuring SignalR hubs:
| Option | Default Value | Description |
|---|---|---|
ClientTimeoutInterval |
30 seconds | The server considers the client disconnected if it hasn't received a message (including keep-alive) in this interval. It could take longer than this timeout interval for the client to be marked disconnected due to how this is implemented. The recommended value is double the KeepAliveInterval value. |
HandshakeTimeout |
15 seconds | If the client doesn't send an initial handshake message within this time interval, the connection is closed. This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | If the server hasn't sent a message within this interval, a ping message is sent automatically to keep the connection open. When changing KeepAliveInterval, change the ServerTimeout or serverTimeoutInMilliseconds setting on the client. The recommended ServerTimeout or serverTimeoutInMilliseconds value is double the KeepAliveInterval value. |
SupportedProtocols |
All installed protocols | Protocols supported by this hub. By default, all protocols registered on the server are allowed. Protocols can be removed from this list to disable specific protocols for individual hubs. |
EnableDetailedErrors |
false |
If true, detailed exception messages are returned to clients when an exception is thrown in a Hub method. The default is false because these exception messages can contain sensitive information. |
StreamBufferCapacity |
10 |
The maximum number of items that can be buffered for client upload streams. If this limit is reached, the processing of invocations is blocked until the server processes stream items. |
MaximumReceiveMessageSize |
32 KB | Maximum size of a single incoming hub message. Increasing the value may increase the risk of Denial of service (DoS) attacks. |
Options can be configured for all hubs by providing an options delegate to the AddSignalR call in Startup.ConfigureServices.
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(1);
});
}
Options for a single hub override the global options provided in AddSignalR and can be configured using AddHubOptions:
services.AddSignalR().AddHubOptions<ChatHub>(options =>
{
options.EnableDetailedErrors = true;
});
Advanced HTTP configuration options
Use HttpConnectionDispatcherOptions to configure advanced settings related to transports and memory buffer management. These options are configured by passing a delegate to MapHub in Startup.Configure.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub", options =>
{
options.Transports =
HttpTransportType.WebSockets |
HttpTransportType.LongPolling;
});
});
}
The following table describes options for configuring ASP.NET Core SignalR's advanced HTTP options:
| Option | Default Value | Description |
|---|---|---|
ApplicationMaxBufferSize |
32 KB | The maximum number of bytes received from the client that the server buffers before applying backpressure. Increasing this value allows the server to receive larger messages more quickly without applying backpressure, but can increase memory consumption. |
AuthorizationData |
Data automatically gathered from the Authorize attributes applied to the Hub class. |
A list of IAuthorizeData objects used to determine if a client is authorized to connect to the hub. |
TransportMaxBufferSize |
32 KB | The maximum number of bytes sent by the app that the server buffers before observing backpressure. Increasing this value allows the server to buffer larger messages more quickly without awaiting backpressure, but can increase memory consumption. |
Transports |
All Transports are enabled. | A bit flags enum of HttpTransportType values that can restrict the transports a client can use to connect. |
LongPolling |
See below. | Additional options specific to the Long Polling transport. |
WebSockets |
See below. | Additional options specific to the WebSockets transport. |
The Long Polling transport has additional options that can be configured using the LongPolling property:
| Option | Default Value | Description |
|---|---|---|
PollTimeout |
90 seconds | The maximum amount of time the server waits for a message to send to the client before terminating a single poll request. Decreasing this value causes the client to issue new poll requests more frequently. |
The WebSocket transport has additional options that can be configured using the WebSockets property:
| Option | Default Value | Description |
|---|---|---|
CloseTimeout |
5 seconds | After the server closes, if the client fails to close within this time interval, the connection is terminated. |
SubProtocolSelector |
null |
A delegate that can be used to set the Sec-WebSocket-Protocol header to a custom value. The delegate receives the values requested by the client as input and is expected to return the desired value. |
Configure client options
Client options can be configured on the HubConnectionBuilder type (available in the .NET and JavaScript clients). It's also available in the Java client, but the HttpHubConnectionBuilder subclass is what contains the builder configuration options, as well as on the HubConnection itself.
Configure logging
Logging is configured in the .NET Client using the ConfigureLogging method. Logging providers and filters can be registered in the same way as they are on the server. See the Logging in ASP.NET Core documentation for more information.
Note
In order to register Logging providers, you must install the necessary packages. See the Built-in logging providers section of the docs for a full list.
For example, to enable Console logging, install the Microsoft.Extensions.Logging.Console NuGet package. Call the AddConsole extension method:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub")
.ConfigureLogging(logging => {
logging.SetMinimumLevel(LogLevel.Information);
logging.AddConsole();
})
.Build();
In the JavaScript client, a similar configureLogging method exists. Provide a LogLevel value indicating the minimum level of log messages to produce. Logs are written to the browser console window.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging(signalR.LogLevel.Information)
.build();
Instead of a LogLevel value, you can also provide a string value representing a log level name. This is useful when configuring SignalR logging in environments where you don't have access to the LogLevel constants.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging("warn")
.build();
The following table lists the available log levels. The value you provide to configureLogging sets the minimum log level that will be logged. Messages logged at this level, or the levels listed after it in the table, will be logged.
| String | LogLevel |
|---|---|
trace |
LogLevel.Trace |
debug |
LogLevel.Debug |
info or information |
LogLevel.Information |
warn or warning |
LogLevel.Warning |
error |
LogLevel.Error |
critical |
LogLevel.Critical |
none |
LogLevel.None |
Note
To disable logging entirely, specify signalR.LogLevel.None in the configureLogging method.
For more information on logging, see the SignalR Diagnostics documentation.
The SignalR Java client uses the SLF4J library for logging. It's a high-level logging API that allows users of the library to choose their own specific logging implementation by bringing in a specific logging dependency. The following code snippet shows how to use java.util.logging with the SignalR Java client.
implementation 'org.slf4j:slf4j-jdk14:1.7.25'
If you don't configure logging in your dependencies, SLF4J loads a default no-operation logger with the following warning message:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
This can safely be ignored.
Configure allowed transports
The transports used by SignalR can be configured in the WithUrl call (withUrl in JavaScript). A bitwise-OR of the values of HttpTransportType can be used to restrict the client to only use the specified transports. All transports are enabled by default.
For example, to disable the Server-Sent Events transport, but allow WebSockets and Long Polling connections:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", HttpTransportType.WebSockets | HttpTransportType.LongPolling)
.Build();
In the JavaScript client, transports are configured by setting the transport field on the options object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", { transport: signalR.HttpTransportType.WebSockets | signalR.HttpTransportType.LongPolling })
.build();
In this version of the Java client WebSockets is the only available transport.
In the Java client, the transport is selected with the withTransport method on the HttpHubConnectionBuilder. The Java client defaults to using the WebSockets transport.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withTransport(TransportEnum.WEBSOCKETS)
.build();
Note
The SignalR Java client doesn't support transport fallback yet.
Configure bearer authentication
To provide authentication data along with SignalR requests, use the AccessTokenProvider option (accessTokenFactory in JavaScript) to specify a function that returns the desired access token. In the .NET Client, this access token is passed in as an HTTP "Bearer Authentication" token (Using the Authorization header with a type of Bearer). In the JavaScript client, the access token is used as a Bearer token, except in a few cases where browser APIs restrict the ability to apply headers (specifically, in Server-Sent Events and WebSockets requests). In these cases, the access token is provided as a query string value access_token.
In the .NET client, the AccessTokenProvider option can be specified using the options delegate in WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.AccessTokenProvider = async () => {
// Get and return the access token.
};
})
.Build();
In the JavaScript client, the access token is configured by setting the accessTokenFactory field on the options object in withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
accessTokenFactory: () => {
// Get and return the access token.
// This function can return a JavaScript Promise if asynchronous
// logic is required to retrieve the access token.
}
})
.build();
In the SignalR Java client, you can configure a bearer token to use for authentication by providing an access token factory to the HttpHubConnectionBuilder. Use withAccessTokenFactory to provide an RxJava Single<String>. With a call to Single.defer, you can write logic to produce access tokens for your client.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withAccessTokenProvider(Single.defer(() -> {
// Your logic here.
return Single.just("An Access Token");
})).build();
Configure timeout and keep-alive options
Additional options for configuring timeout and keep-alive behavior are available on the HubConnection object itself:
| Option | Default value | Description |
|---|---|---|
ServerTimeout |
30 seconds (30,000 milliseconds) | Timeout for server activity. If the server hasn't sent a message in this interval, the client considers the server disconnected and triggers the Closed event (onclose in JavaScript). This value must be large enough for a ping message to be sent from the server and received by the client within the timeout interval. The recommended value is a number at least double the server's KeepAliveInterval value to allow time for pings to arrive. |
HandshakeTimeout |
15 seconds | Timeout for initial server handshake. If the server doesn't send a handshake response in this interval, the client cancels the handshake and triggers the Closed event (onclose in JavaScript). This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | Determines the interval at which the client sends ping messages. Sending any message from the client resets the timer to the start of the interval. If the client hasn't sent a message in the ClientTimeoutInterval set on the server, the server considers the client disconnected. |
In the .NET Client, timeout values are specified as TimeSpan values.
Configure additional options
Additional options can be configured in the WithUrl (withUrl in JavaScript) method on HubConnectionBuilder or on the various configuration APIs on the HttpHubConnectionBuilder in the Java client:
| .NET Option | Default value | Description |
|---|---|---|
AccessTokenProvider |
null |
A function returning a string that is provided as a Bearer authentication token in HTTP requests. |
SkipNegotiation |
false |
Set this to true to skip the negotiation step. Only supported when the WebSockets transport is the only enabled transport. This setting can't be enabled when using the Azure SignalR Service. |
ClientCertificates |
Empty | A collection of TLS certificates to send to authenticate requests. |
Cookies |
Empty | A collection of HTTP cookies to send with every HTTP request. |
Credentials |
Empty | Credentials to send with every HTTP request. |
CloseTimeout |
5 seconds | WebSockets only. The maximum amount of time the client waits after closing for the server to acknowledge the close request. If the server doesn't acknowledge the close within this time, the client disconnects. |
Headers |
Empty | A Map of additional HTTP headers to send with every HTTP request. |
HttpMessageHandlerFactory |
null |
A delegate that can be used to configure or replace the HttpMessageHandler used to send HTTP requests. Not used for WebSocket connections. This delegate must return a non-null value, and it receives the default value as a parameter. Either modify settings on that default value and return it, or return a new HttpMessageHandler instance. When replacing the handler make sure to copy the settings you want to keep from the provided handler, otherwise, the configured options (such as Cookies and Headers) won't apply to the new handler. |
Proxy |
null |
An HTTP proxy to use when sending HTTP requests. |
UseDefaultCredentials |
false |
Set this boolean to send the default credentials for HTTP and WebSockets requests. This enables the use of Windows authentication. |
WebSocketConfiguration |
null |
A delegate that can be used to configure additional WebSocket options. Receives an instance of ClientWebSocketOptions that can be used to configure the options. |
In the .NET Client, these options can be modified by the options delegate provided to WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.Headers["Foo"] = "Bar";
options.Cookies.Add(new Cookie(/* ... */);
options.ClientCertificates.Add(/* ... */);
})
.Build();
In the JavaScript Client, these options can be provided in a JavaScript object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.build();
In the Java client, these options can be configured with the methods on the HttpHubConnectionBuilder returned from the HubConnectionBuilder.create("HUB URL")
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withHeader("Foo", "Bar")
.shouldSkipNegotiate(true)
.withHandshakeResponseTimeout(30*1000)
.build();
Additional resources
JSON/MessagePack serialization options
ASP.NET Core SignalR supports two protocols for encoding messages: JSON and MessagePack. Each protocol has serialization configuration options.
JSON serialization can be configured on the server using the AddJsonProtocol extension method. AddJsonProtocol can be added after AddSignalR in Startup.ConfigureServices. The AddJsonProtocol method takes a delegate that receives an options object. The PayloadSerializerOptions property on that object is a System.Text.Json JsonSerializerOptions object that can be used to configure serialization of arguments and return values. For more information, see the System.Text.Json documentation.
For example, to configure the serializer to not change the casing of property names, rather than the default camel case names, use the following code in Startup.ConfigureServices:
services.AddSignalR()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null
});
In the .NET client, the same AddJsonProtocol extension method exists on HubConnectionBuilder. The Microsoft.Extensions.DependencyInjection namespace must be imported to resolve the extension method:
// At the top of the file:
using Microsoft.Extensions.DependencyInjection;
// When constructing your connection:
var connection = new HubConnectionBuilder()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
})
.Build();
Note
It's not possible to configure JSON serialization in the JavaScript client at this time.
Switch to Newtonsoft.Json
If you need features of Newtonsoft.Json that aren't supported in System.Text.Json, see Switch to Newtonsoft.Json.
MessagePack serialization options
MessagePack serialization can be configured by providing a delegate to the AddMessagePackProtocol call. See MessagePack in SignalR for more details.
Note
It's not possible to configure MessagePack serialization in the JavaScript client at this time.
Configure server options
The following table describes options for configuring SignalR hubs:
| Option | Default Value | Description |
|---|---|---|
ClientTimeoutInterval |
30 seconds | The server considers the client disconnected if it hasn't received a message (including keep-alive) in this interval. It could take longer than this timeout interval for the client to be marked disconnected due to how this is implemented. The recommended value is double the KeepAliveInterval value. |
HandshakeTimeout |
15 seconds | If the client doesn't send an initial handshake message within this time interval, the connection is closed. This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | If the server hasn't sent a message within this interval, a ping message is sent automatically to keep the connection open. When changing KeepAliveInterval, change the ServerTimeout or serverTimeoutInMilliseconds setting on the client. The recommended ServerTimeout or serverTimeoutInMilliseconds value is double the KeepAliveInterval value. |
SupportedProtocols |
All installed protocols | Protocols supported by this hub. By default, all protocols registered on the server are allowed. Protocols can be removed from this list to disable specific protocols for individual hubs. |
EnableDetailedErrors |
false |
If true, detailed exception messages are returned to clients when an exception is thrown in a Hub method. The default is false because these exception messages can contain sensitive information. |
StreamBufferCapacity |
10 |
The maximum number of items that can be buffered for client upload streams. If this limit is reached, the processing of invocations is blocked until the server processes stream items. |
MaximumReceiveMessageSize |
32 KB | Maximum size of a single incoming hub message. Increasing the value may increase the risk of Denial of service (DoS) attacks. |
Options can be configured for all hubs by providing an options delegate to the AddSignalR call in Startup.ConfigureServices.
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(1);
});
}
Options for a single hub override the global options provided in AddSignalR and can be configured using AddHubOptions:
services.AddSignalR().AddHubOptions<ChatHub>(options =>
{
options.EnableDetailedErrors = true;
});
Advanced HTTP configuration options
Use HttpConnectionDispatcherOptions to configure advanced settings related to transports and memory buffer management. These options are configured by passing a delegate to MapHub in Startup.Configure.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub", options =>
{
options.Transports =
HttpTransportType.WebSockets |
HttpTransportType.LongPolling;
});
});
}
The following table describes options for configuring ASP.NET Core SignalR's advanced HTTP options:
| Option | Default Value | Description |
|---|---|---|
ApplicationMaxBufferSize |
32 KB | The maximum number of bytes received from the client that the server buffers before applying backpressure. Increasing this value allows the server to receive larger messages more quickly without applying backpressure, but can increase memory consumption. |
AuthorizationData |
Data automatically gathered from the Authorize attributes applied to the Hub class. |
A list of IAuthorizeData objects used to determine if a client is authorized to connect to the hub. |
TransportMaxBufferSize |
32 KB | The maximum number of bytes sent by the app that the server buffers before observing backpressure. Increasing this value allows the server to buffer larger messages more quickly without awaiting backpressure, but can increase memory consumption. |
Transports |
All Transports are enabled. | A bit flags enum of HttpTransportType values that can restrict the transports a client can use to connect. |
LongPolling |
See below. | Additional options specific to the Long Polling transport. |
WebSockets |
See below. | Additional options specific to the WebSockets transport. |
MinimumProtocolVersion |
0 | Specify the minimum version of the negotiate protocol. This is used to limit clients to newer versions. |
The Long Polling transport has additional options that can be configured using the LongPolling property:
| Option | Default Value | Description |
|---|---|---|
PollTimeout |
90 seconds | The maximum amount of time the server waits for a message to send to the client before terminating a single poll request. Decreasing this value causes the client to issue new poll requests more frequently. |
The WebSocket transport has additional options that can be configured using the WebSockets property:
| Option | Default Value | Description |
|---|---|---|
CloseTimeout |
5 seconds | After the server closes, if the client fails to close within this time interval, the connection is terminated. |
SubProtocolSelector |
null |
A delegate that can be used to set the Sec-WebSocket-Protocol header to a custom value. The delegate receives the values requested by the client as input and is expected to return the desired value. |
Configure client options
Client options can be configured on the HubConnectionBuilder type (available in the .NET and JavaScript clients). It's also available in the Java client, but the HttpHubConnectionBuilder subclass is what contains the builder configuration options, as well as on the HubConnection itself.
Configure logging
Logging is configured in the .NET Client using the ConfigureLogging method. Logging providers and filters can be registered in the same way as they are on the server. See the Logging in ASP.NET Core documentation for more information.
Note
In order to register Logging providers, you must install the necessary packages. See the Built-in logging providers section of the docs for a full list.
For example, to enable Console logging, install the Microsoft.Extensions.Logging.Console NuGet package. Call the AddConsole extension method:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub")
.ConfigureLogging(logging => {
logging.SetMinimumLevel(LogLevel.Information);
logging.AddConsole();
})
.Build();
In the JavaScript client, a similar configureLogging method exists. Provide a LogLevel value indicating the minimum level of log messages to produce. Logs are written to the browser console window.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging(signalR.LogLevel.Information)
.build();
Instead of a LogLevel value, you can also provide a string value representing a log level name. This is useful when configuring SignalR logging in environments where you don't have access to the LogLevel constants.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging("warn")
.build();
The following table lists the available log levels. The value you provide to configureLogging sets the minimum log level that will be logged. Messages logged at this level, or the levels listed after it in the table, will be logged.
| String | LogLevel |
|---|---|
trace |
LogLevel.Trace |
debug |
LogLevel.Debug |
info or information |
LogLevel.Information |
warn or warning |
LogLevel.Warning |
error |
LogLevel.Error |
critical |
LogLevel.Critical |
none |
LogLevel.None |
Note
To disable logging entirely, specify signalR.LogLevel.None in the configureLogging method.
For more information on logging, see the SignalR Diagnostics documentation.
The SignalR Java client uses the SLF4J library for logging. It's a high-level logging API that allows users of the library to choose their own specific logging implementation by bringing in a specific logging dependency. The following code snippet shows how to use java.util.logging with the SignalR Java client.
implementation 'org.slf4j:slf4j-jdk14:1.7.25'
If you don't configure logging in your dependencies, SLF4J loads a default no-operation logger with the following warning message:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
This can safely be ignored.
Configure allowed transports
The transports used by SignalR can be configured in the WithUrl call (withUrl in JavaScript). A bitwise-OR of the values of HttpTransportType can be used to restrict the client to only use the specified transports. All transports are enabled by default.
For example, to disable the Server-Sent Events transport, but allow WebSockets and Long Polling connections:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", HttpTransportType.WebSockets | HttpTransportType.LongPolling)
.Build();
In the JavaScript client, transports are configured by setting the transport field on the options object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", { transport: signalR.HttpTransportType.WebSockets | signalR.HttpTransportType.LongPolling })
.build();
In this version of the Java client WebSockets is the only available transport.
In the Java client, the transport is selected with the withTransport method on the HttpHubConnectionBuilder. The Java client defaults to using the WebSockets transport.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withTransport(TransportEnum.WEBSOCKETS)
.build();
Note
The SignalR Java client doesn't support transport fallback yet.
Configure bearer authentication
To provide authentication data along with SignalR requests, use the AccessTokenProvider option (accessTokenFactory in JavaScript) to specify a function that returns the desired access token. In the .NET Client, this access token is passed in as an HTTP "Bearer Authentication" token (Using the Authorization header with a type of Bearer). In the JavaScript client, the access token is used as a Bearer token, except in a few cases where browser APIs restrict the ability to apply headers (specifically, in Server-Sent Events and WebSockets requests). In these cases, the access token is provided as a query string value access_token.
In the .NET client, the AccessTokenProvider option can be specified using the options delegate in WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.AccessTokenProvider = async () => {
// Get and return the access token.
};
})
.Build();
In the JavaScript client, the access token is configured by setting the accessTokenFactory field on the options object in withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
accessTokenFactory: () => {
// Get and return the access token.
// This function can return a JavaScript Promise if asynchronous
// logic is required to retrieve the access token.
}
})
.build();
In the SignalR Java client, you can configure a bearer token to use for authentication by providing an access token factory to the HttpHubConnectionBuilder. Use withAccessTokenFactory to provide an RxJava Single<String>. With a call to Single.defer, you can write logic to produce access tokens for your client.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withAccessTokenProvider(Single.defer(() -> {
// Your logic here.
return Single.just("An Access Token");
})).build();
Configure timeout and keep-alive options
Additional options for configuring timeout and keep-alive behavior are available on the HubConnection object itself:
| Option | Default value | Description |
|---|---|---|
ServerTimeout |
30 seconds (30,000 milliseconds) | Timeout for server activity. If the server hasn't sent a message in this interval, the client considers the server disconnected and triggers the Closed event (onclose in JavaScript). This value must be large enough for a ping message to be sent from the server and received by the client within the timeout interval. The recommended value is a number at least double the server's KeepAliveInterval value to allow time for pings to arrive. |
HandshakeTimeout |
15 seconds | Timeout for initial server handshake. If the server doesn't send a handshake response in this interval, the client cancels the handshake and triggers the Closed event (onclose in JavaScript). This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | Determines the interval at which the client sends ping messages. Sending any message from the client resets the timer to the start of the interval. If the client hasn't sent a message in the ClientTimeoutInterval set on the server, the server considers the client disconnected. |
In the .NET Client, timeout values are specified as TimeSpan values.
Configure additional options
Additional options can be configured in the WithUrl (withUrl in JavaScript) method on HubConnectionBuilder or on the various configuration APIs on the HttpHubConnectionBuilder in the Java client:
| .NET Option | Default value | Description |
|---|---|---|
AccessTokenProvider |
null |
A function returning a string that is provided as a Bearer authentication token in HTTP requests. |
SkipNegotiation |
false |
Set this to true to skip the negotiation step. Only supported when the WebSockets transport is the only enabled transport. This setting can't be enabled when using the Azure SignalR Service. |
ClientCertificates |
Empty | A collection of TLS certificates to send to authenticate requests. |
Cookies |
Empty | A collection of HTTP cookies to send with every HTTP request. |
Credentials |
Empty | Credentials to send with every HTTP request. |
CloseTimeout |
5 seconds | WebSockets only. The maximum amount of time the client waits after closing for the server to acknowledge the close request. If the server doesn't acknowledge the close within this time, the client disconnects. |
Headers |
Empty | A Map of additional HTTP headers to send with every HTTP request. |
HttpMessageHandlerFactory |
null |
A delegate that can be used to configure or replace the HttpMessageHandler used to send HTTP requests. Not used for WebSocket connections. This delegate must return a non-null value, and it receives the default value as a parameter. Either modify settings on that default value and return it, or return a new HttpMessageHandler instance. When replacing the handler make sure to copy the settings you want to keep from the provided handler, otherwise, the configured options (such as Cookies and Headers) won't apply to the new handler. |
Proxy |
null |
An HTTP proxy to use when sending HTTP requests. |
UseDefaultCredentials |
false |
Set this boolean to send the default credentials for HTTP and WebSockets requests. This enables the use of Windows authentication. |
WebSocketConfiguration |
null |
A delegate that can be used to configure additional WebSocket options. Receives an instance of ClientWebSocketOptions that can be used to configure the options. |
In the .NET Client, these options can be modified by the options delegate provided to WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.Headers["Foo"] = "Bar";
options.Cookies.Add(new Cookie(/* ... */);
options.ClientCertificates.Add(/* ... */);
})
.Build();
In the JavaScript Client, these options can be provided in a JavaScript object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.build();
In the Java client, these options can be configured with the methods on the HttpHubConnectionBuilder returned from the HubConnectionBuilder.create("HUB URL")
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withHeader("Foo", "Bar")
.shouldSkipNegotiate(true)
.withHandshakeResponseTimeout(30*1000)
.build();
Additional resources
JSON/MessagePack serialization options
ASP.NET Core SignalR supports two protocols for encoding messages: JSON and MessagePack. Each protocol has serialization configuration options.
JSON serialization can be configured on the server using the AddJsonProtocol extension method. AddJsonProtocol can be added after AddSignalR in Startup.ConfigureServices. The AddJsonProtocol method takes a delegate that receives an options object. The PayloadSerializerOptions property on that object is a System.Text.Json JsonSerializerOptions object that can be used to configure serialization of arguments and return values. For more information, see the System.Text.Json documentation.
For example, to configure the serializer to not change the casing of property names, rather than the default camel case names, use the following code in Startup.ConfigureServices:
services.AddSignalR()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
});
In the .NET client, the same AddJsonProtocol extension method exists on HubConnectionBuilder. The Microsoft.Extensions.DependencyInjection namespace must be imported to resolve the extension method:
// At the top of the file:
using Microsoft.Extensions.DependencyInjection;
// When constructing your connection:
var connection = new HubConnectionBuilder()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
})
.Build();
Note
It's not possible to configure JSON serialization in the JavaScript client at this time.
Switch to Newtonsoft.Json
If you need features of Newtonsoft.Json that aren't supported in System.Text.Json, see Switch to Newtonsoft.Json.
MessagePack serialization options
MessagePack serialization can be configured by providing a delegate to the AddMessagePackProtocol call. See MessagePack in SignalR for more details.
Note
It's not possible to configure MessagePack serialization in the JavaScript client at this time.
Configure server options
The following table describes options for configuring SignalR hubs:
| Option | Default Value | Description |
|---|---|---|
ClientTimeoutInterval |
30 seconds | The server considers the client disconnected if it hasn't received a message (including keep-alive) in this interval. It could take longer than this timeout interval for the client to be marked disconnected due to how this is implemented. The recommended value is double the KeepAliveInterval value. |
HandshakeTimeout |
15 seconds | If the client doesn't send an initial handshake message within this time interval, the connection is closed. This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | If the server hasn't sent a message within this interval, a ping message is sent automatically to keep the connection open. When changing KeepAliveInterval, change the ServerTimeout or serverTimeoutInMilliseconds setting on the client. The recommended ServerTimeout or serverTimeoutInMilliseconds value is double the KeepAliveInterval value. |
SupportedProtocols |
All installed protocols | Protocols supported by this hub. By default, all protocols registered on the server are allowed. Protocols can be removed from this list to disable specific protocols for individual hubs. |
EnableDetailedErrors |
false |
If true, detailed exception messages are returned to clients when an exception is thrown in a Hub method. The default is false because these exception messages can contain sensitive information. |
StreamBufferCapacity |
10 |
The maximum number of items that can be buffered for client upload streams. If this limit is reached, the processing of invocations is blocked until the server processes stream items. |
MaximumReceiveMessageSize |
32 KB | Maximum size of a single incoming hub message. Increasing the value may increase the risk of Denial of service (DoS) attacks. |
MaximumParallelInvocationsPerClient |
1 | The maximum number of hub methods that each client can call in parallel before queueing. |
Options can be configured for all hubs by providing an options delegate to the AddSignalR call in Startup.ConfigureServices.
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(1);
});
}
Options for a single hub override the global options provided in AddSignalR and can be configured using AddHubOptions:
services.AddSignalR().AddHubOptions<ChatHub>(options =>
{
options.EnableDetailedErrors = true;
});
Advanced HTTP configuration options
Use HttpConnectionDispatcherOptions to configure advanced settings related to transports and memory buffer management. These options are configured by passing a delegate to MapHub in Startup.Configure.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub", options =>
{
options.Transports =
HttpTransportType.WebSockets |
HttpTransportType.LongPolling;
});
});
}
The following table describes options for configuring ASP.NET Core SignalR's advanced HTTP options:
| Option | Default Value | Description |
|---|---|---|
ApplicationMaxBufferSize |
32 KB | The maximum number of bytes received from the client that the server buffers before applying backpressure. Increasing this value allows the server to receive larger messages more quickly without applying backpressure, but can increase memory consumption. |
AuthorizationData |
Data automatically gathered from the Authorize attributes applied to the Hub class. |
A list of IAuthorizeData objects used to determine if a client is authorized to connect to the hub. |
TransportMaxBufferSize |
32 KB | The maximum number of bytes sent by the app that the server buffers before observing backpressure. Increasing this value allows the server to buffer larger messages more quickly without awaiting backpressure, but can increase memory consumption. |
Transports |
All Transports are enabled. | A bit flags enum of HttpTransportType values that can restrict the transports a client can use to connect. |
LongPolling |
See below. | Additional options specific to the Long Polling transport. |
WebSockets |
See below. | Additional options specific to the WebSockets transport. |
MinimumProtocolVersion |
0 | Specify the minimum version of the negotiate protocol. This is used to limit clients to newer versions. |
The Long Polling transport has additional options that can be configured using the LongPolling property:
| Option | Default Value | Description |
|---|---|---|
PollTimeout |
90 seconds | The maximum amount of time the server waits for a message to send to the client before terminating a single poll request. Decreasing this value causes the client to issue new poll requests more frequently. |
The WebSocket transport has additional options that can be configured using the WebSockets property:
| Option | Default Value | Description |
|---|---|---|
CloseTimeout |
5 seconds | After the server closes, if the client fails to close within this time interval, the connection is terminated. |
SubProtocolSelector |
null |
A delegate that can be used to set the Sec-WebSocket-Protocol header to a custom value. The delegate receives the values requested by the client as input and is expected to return the desired value. |
Configure client options
Client options can be configured on the HubConnectionBuilder type (available in the .NET and JavaScript clients). It's also available in the Java client, but the HttpHubConnectionBuilder subclass is what contains the builder configuration options, as well as on the HubConnection itself.
Configure logging
Logging is configured in the .NET Client using the ConfigureLogging method. Logging providers and filters can be registered in the same way as they are on the server. See the Logging in ASP.NET Core documentation for more information.
Note
In order to register Logging providers, you must install the necessary packages. See the Built-in logging providers section of the docs for a full list.
For example, to enable Console logging, install the Microsoft.Extensions.Logging.Console NuGet package. Call the AddConsole extension method:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub")
.ConfigureLogging(logging => {
logging.SetMinimumLevel(LogLevel.Information);
logging.AddConsole();
})
.Build();
In the JavaScript client, a similar configureLogging method exists. Provide a LogLevel value indicating the minimum level of log messages to produce. Logs are written to the browser console window.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging(signalR.LogLevel.Information)
.build();
Instead of a LogLevel value, you can also provide a string value representing a log level name. This is useful when configuring SignalR logging in environments where you don't have access to the LogLevel constants.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging("warn")
.build();
The following table lists the available log levels. The value you provide to configureLogging sets the minimum log level that will be logged. Messages logged at this level, or the levels listed after it in the table, will be logged.
| String | LogLevel |
|---|---|
trace |
LogLevel.Trace |
debug |
LogLevel.Debug |
info or information |
LogLevel.Information |
warn or warning |
LogLevel.Warning |
error |
LogLevel.Error |
critical |
LogLevel.Critical |
none |
LogLevel.None |
Note
To disable logging entirely, specify signalR.LogLevel.None in the configureLogging method.
For more information on logging, see the SignalR Diagnostics documentation.
The SignalR Java client uses the SLF4J library for logging. It's a high-level logging API that allows users of the library to choose their own specific logging implementation by bringing in a specific logging dependency. The following code snippet shows how to use java.util.logging with the SignalR Java client.
implementation 'org.slf4j:slf4j-jdk14:1.7.25'
If you don't configure logging in your dependencies, SLF4J loads a default no-operation logger with the following warning message:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
This can safely be ignored.
Configure allowed transports
The transports used by SignalR can be configured in the WithUrl call (withUrl in JavaScript). A bitwise-OR of the values of HttpTransportType can be used to restrict the client to only use the specified transports. All transports are enabled by default.
For example, to disable the Server-Sent Events transport, but allow WebSockets and Long Polling connections:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", HttpTransportType.WebSockets | HttpTransportType.LongPolling)
.Build();
In the JavaScript client, transports are configured by setting the transport field on the options object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", { transport: signalR.HttpTransportType.WebSockets | signalR.HttpTransportType.LongPolling })
.build();
In this version of the Java client WebSockets is the only available transport.
In the Java client, the transport is selected with the withTransport method on the HttpHubConnectionBuilder. The Java client defaults to using the WebSockets transport.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withTransport(TransportEnum.WEBSOCKETS)
.build();
Note
The SignalR Java client doesn't support transport fallback yet.
Configure bearer authentication
To provide authentication data along with SignalR requests, use the AccessTokenProvider option (accessTokenFactory in JavaScript) to specify a function that returns the desired access token. In the .NET Client, this access token is passed in as an HTTP "Bearer Authentication" token (Using the Authorization header with a type of Bearer). In the JavaScript client, the access token is used as a Bearer token, except in a few cases where browser APIs restrict the ability to apply headers (specifically, in Server-Sent Events and WebSockets requests). In these cases, the access token is provided as a query string value access_token.
In the .NET client, the AccessTokenProvider option can be specified using the options delegate in WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.AccessTokenProvider = async () => {
// Get and return the access token.
};
})
.Build();
In the JavaScript client, the access token is configured by setting the accessTokenFactory field on the options object in withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
accessTokenFactory: () => {
// Get and return the access token.
// This function can return a JavaScript Promise if asynchronous
// logic is required to retrieve the access token.
}
})
.build();
In the SignalR Java client, you can configure a bearer token to use for authentication by providing an access token factory to the HttpHubConnectionBuilder. Use withAccessTokenFactory to provide an RxJava Single<String>. With a call to Single.defer, you can write logic to produce access tokens for your client.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withAccessTokenProvider(Single.defer(() -> {
// Your logic here.
return Single.just("An Access Token");
})).build();
Configure timeout and keep-alive options
Additional options for configuring timeout and keep-alive behavior are available on the HubConnection object itself:
| Option | Default value | Description |
|---|---|---|
ServerTimeout |
30 seconds (30,000 milliseconds) | Timeout for server activity. If the server hasn't sent a message in this interval, the client considers the server disconnected and triggers the Closed event (onclose in JavaScript). This value must be large enough for a ping message to be sent from the server and received by the client within the timeout interval. The recommended value is a number at least double the server's KeepAliveInterval value to allow time for pings to arrive. |
HandshakeTimeout |
15 seconds | Timeout for initial server handshake. If the server doesn't send a handshake response in this interval, the client cancels the handshake and triggers the Closed event (onclose in JavaScript). This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | Determines the interval at which the client sends ping messages. Sending any message from the client resets the timer to the start of the interval. If the client hasn't sent a message in the ClientTimeoutInterval set on the server, the server considers the client disconnected. |
In the .NET Client, timeout values are specified as TimeSpan values.
Configure additional options
Additional options can be configured in the WithUrl (withUrl in JavaScript) method on HubConnectionBuilder or on the various configuration APIs on the HttpHubConnectionBuilder in the Java client:
| .NET Option | Default value | Description |
|---|---|---|
AccessTokenProvider |
null |
A function returning a string that is provided as a Bearer authentication token in HTTP requests. |
SkipNegotiation |
false |
Set this to true to skip the negotiation step. Only supported when the WebSockets transport is the only enabled transport. This setting can't be enabled when using the Azure SignalR Service. |
ClientCertificates |
Empty | A collection of TLS certificates to send to authenticate requests. |
Cookies |
Empty | A collection of HTTP cookies to send with every HTTP request. |
Credentials |
Empty | Credentials to send with every HTTP request. |
CloseTimeout |
5 seconds | WebSockets only. The maximum amount of time the client waits after closing for the server to acknowledge the close request. If the server doesn't acknowledge the close within this time, the client disconnects. |
Headers |
Empty | A Map of additional HTTP headers to send with every HTTP request. |
HttpMessageHandlerFactory |
null |
A delegate that can be used to configure or replace the HttpMessageHandler used to send HTTP requests. Not used for WebSocket connections. This delegate must return a non-null value, and it receives the default value as a parameter. Either modify settings on that default value and return it, or return a new HttpMessageHandler instance. When replacing the handler make sure to copy the settings you want to keep from the provided handler, otherwise, the configured options (such as Cookies and Headers) won't apply to the new handler. |
Proxy |
null |
An HTTP proxy to use when sending HTTP requests. |
UseDefaultCredentials |
false |
Set this boolean to send the default credentials for HTTP and WebSockets requests. This enables the use of Windows authentication. |
WebSocketConfiguration |
null |
A delegate that can be used to configure additional WebSocket options. Receives an instance of ClientWebSocketOptions that can be used to configure the options. |
In the .NET Client, these options can be modified by the options delegate provided to WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.Headers["Foo"] = "Bar";
options.SkipNegotiation = true;
options.Transports = HttpTransportType.WebSockets;
options.Cookies.Add(new Cookie(/* ... */);
options.ClientCertificates.Add(/* ... */);
})
.Build();
In the JavaScript Client, these options can be provided in a JavaScript object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
// "Foo: Bar" will not be sent with WebSockets or Server-Sent Events requests
headers: { "Foo": "Bar" },
transport: signalR.HttpTransportType.LongPolling
})
.build();
In the Java client, these options can be configured with the methods on the HttpHubConnectionBuilder returned from the HubConnectionBuilder.create("HUB URL")
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withHeader("Foo", "Bar")
.shouldSkipNegotiate(true)
.withHandshakeResponseTimeout(30*1000)
.build();
Additional resources
JSON/MessagePack serialization options
ASP.NET Core SignalR supports two protocols for encoding messages: JSON and MessagePack. Each protocol has serialization configuration options.
JSON serialization can be configured on the server using the AddJsonProtocol extension method. AddJsonProtocol can be added after AddSignalR in Program.cs. The AddJsonProtocol method takes a delegate that receives an options object. The PayloadSerializerOptions property on that object is a System.Text.Json JsonSerializerOptions object that can be used to configure serialization of arguments and return values. For more information, see the System.Text.Json documentation.
For example, to configure the serializer to not change the casing of property names, rather than the default camel case names, use the following code in Program.cs:
builder.Services.AddSignalR()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
});
In the .NET client, the same AddJsonProtocol extension method exists on HubConnectionBuilder. The Microsoft.Extensions.DependencyInjection namespace must be imported to resolve the extension method:
// At the top of the file:
using Microsoft.Extensions.DependencyInjection;
// When constructing your connection:
var connection = new HubConnectionBuilder()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
})
.Build();
Note
It's not possible to configure JSON serialization in the JavaScript client at this time.
Switch to Newtonsoft.Json
If you need features of Newtonsoft.Json that aren't supported in System.Text.Json, see Switch to Newtonsoft.Json.
MessagePack serialization options
MessagePack serialization can be configured by providing a delegate to the AddMessagePackProtocol call. See MessagePack in SignalR for more details.
Note
It's not possible to configure MessagePack serialization in the JavaScript client at this time.
Configure server options
The following table describes options for configuring SignalR hubs:
| Option | Default Value | Description |
|---|---|---|
ClientTimeoutInterval |
30 seconds | The server considers the client disconnected if it hasn't received a message (including keep-alive) in this interval. It could take longer than this timeout interval for the client to be marked disconnected due to how this is implemented. The recommended value is double the KeepAliveInterval value. |
HandshakeTimeout |
15 seconds | If the client doesn't send an initial handshake message within this time interval, the connection is closed. This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | If the server hasn't sent a message within this interval, a ping message is sent automatically to keep the connection open. When changing KeepAliveInterval, change the ServerTimeout or serverTimeoutInMilliseconds setting on the client. The recommended ServerTimeout or serverTimeoutInMilliseconds value is double the KeepAliveInterval value. |
SupportedProtocols |
All installed protocols | Protocols supported by this hub. By default, all protocols registered on the server are allowed. Protocols can be removed from this list to disable specific protocols for individual hubs. |
EnableDetailedErrors |
false |
If true, detailed exception messages are returned to clients when an exception is thrown in a Hub method. The default is false because these exception messages can contain sensitive information. |
StreamBufferCapacity |
10 |
The maximum number of items that can be buffered for client upload streams. If this limit is reached, the processing of invocations is blocked until the server processes stream items. |
MaximumReceiveMessageSize |
32 KB | Maximum size of a single incoming hub message. Increasing the value may increase the risk of Denial of service (DoS) attacks. |
MaximumParallelInvocationsPerClient |
1 | The maximum number of hub methods that each client can call in parallel before queueing. |
Options can be configured for all hubs by providing an options delegate to the AddSignalR call in Program.cs.
builder.Services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(1);
});
Options for a single hub override the global options provided in AddSignalR and can be configured using AddHubOptions:
builder.Services.AddSignalR().AddHubOptions<ChatHub>(options =>
{
options.EnableDetailedErrors = true;
});
Advanced HTTP configuration options
Use HttpConnectionDispatcherOptions to configure advanced settings related to transports and memory buffer management. These options are configured by passing a delegate to MapHub in Program.cs.
using Microsoft.AspNetCore.Http.Connections;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddSignalR();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.MapHub<ChatHub>("/chathub", options =>
{
options.Transports =
HttpTransportType.WebSockets |
HttpTransportType.LongPolling;
}
);
app.Run();
The following table describes options for configuring ASP.NET Core SignalR's advanced HTTP options:
| Option | Default Value | Description |
|---|---|---|
ApplicationMaxBufferSize |
64 KB | The maximum number of bytes received from the client that the server buffers before applying backpressure. Increasing this value allows the server to receive larger messages faster without applying backpressure, but can increase memory consumption. |
TransportMaxBufferSize |
64 KB | The maximum number of bytes sent by the app that the server buffers before observing backpressure. Increasing this value allows the server to buffer larger messages faster without awaiting backpressure, but can increase memory consumption. |
AuthorizationData |
Data automatically gathered from the Authorize attributes applied to the Hub class. |
A list of IAuthorizeData objects used to determine if a client is authorized to connect to the hub. |
Transports |
All Transports are enabled. | A bit flags enum of HttpTransportType values that can restrict the transports a client can use to connect. |
LongPolling |
See below. | Additional options specific to the Long Polling transport. |
WebSockets |
See below. | Additional options specific to the WebSockets transport. |
MinimumProtocolVersion |
0 | Specify the minimum version of the negotiate protocol. This is used to limit clients to newer versions. |
CloseOnAuthenticationExpiration |
false | Set this option to enable authentication expiration tracking which will close connections when a token expires. |
The Long Polling transport has additional options that can be configured using the LongPolling property:
| Option | Default Value | Description |
|---|---|---|
PollTimeout |
90 seconds | The maximum amount of time the server waits for a message to send to the client before terminating a single poll request. Decreasing this value causes the client to issue new poll requests more frequently. |
The WebSocket transport has additional options that can be configured using the WebSockets property:
| Option | Default Value | Description |
|---|---|---|
CloseTimeout |
5 seconds | After the server closes, if the client fails to close within this time interval, the connection is terminated. |
SubProtocolSelector |
null |
A delegate that can be used to set the Sec-WebSocket-Protocol header to a custom value. The delegate receives the values requested by the client as input and is expected to return the desired value. |
Configure client options
Client options can be configured on the HubConnectionBuilder type (available in the .NET and JavaScript clients). It's also available in the Java client, but the HttpHubConnectionBuilder subclass is what contains the builder configuration options, as well as on the HubConnection itself.
Configure logging
Logging is configured in the .NET Client using the ConfigureLogging method. Logging providers and filters can be registered in the same way as they are on the server. See the Logging in ASP.NET Core documentation for more information.
Note
In order to register Logging providers, you must install the necessary packages. See the Built-in logging providers section of the docs for a full list.
For example, to enable Console logging, install the Microsoft.Extensions.Logging.Console NuGet package. Call the AddConsole extension method:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub")
.ConfigureLogging(logging => {
logging.SetMinimumLevel(LogLevel.Information);
logging.AddConsole();
})
.Build();
In the JavaScript client, a similar configureLogging method exists. Provide a LogLevel value indicating the minimum level of log messages to produce. Logs are written to the browser console window.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging(signalR.LogLevel.Information)
.build();
Instead of a LogLevel value, you can also provide a string value representing a log level name. This is useful when configuring SignalR logging in environments where you don't have access to the LogLevel constants.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging("warn")
.build();
The following table lists the available log levels. The value you provide to configureLogging sets the minimum log level that will be logged. Messages logged at this level, or the levels listed after it in the table, will be logged.
| String | LogLevel |
|---|---|
trace |
LogLevel.Trace |
debug |
LogLevel.Debug |
info or information |
LogLevel.Information |
warn or warning |
LogLevel.Warning |
error |
LogLevel.Error |
critical |
LogLevel.Critical |
none |
LogLevel.None |
Note
To disable logging entirely, specify signalR.LogLevel.None in the configureLogging method.
For more information on logging, see the SignalR Diagnostics documentation.
The SignalR Java client uses the SLF4J library for logging. It's a high-level logging API that allows users of the library to choose their own specific logging implementation by bringing in a specific logging dependency. The following code snippet shows how to use java.util.logging with the SignalR Java client.
implementation 'org.slf4j:slf4j-jdk14:1.7.25'
If you don't configure logging in your dependencies, SLF4J loads a default no-operation logger with the following warning message:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
This can safely be ignored.
Configure allowed transports
The transports used by SignalR can be configured in the WithUrl call (withUrl in JavaScript). A bitwise-OR of the values of HttpTransportType can be used to restrict the client to only use the specified transports. All transports are enabled by default.
For example, to disable the Server-Sent Events transport, but allow WebSockets and Long Polling connections:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", HttpTransportType.WebSockets | HttpTransportType.LongPolling)
.Build();
In the JavaScript client, transports are configured by setting the transport field on the options object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", { transport: signalR.HttpTransportType.WebSockets | signalR.HttpTransportType.LongPolling })
.build();
In this version of the Java client WebSockets is the only available transport.
In the Java client, the transport is selected with the withTransport method on the HttpHubConnectionBuilder. The Java client defaults to using the WebSockets transport.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withTransport(TransportEnum.WEBSOCKETS)
.build();
Note
The SignalR Java client doesn't support transport fallback yet.
Configure bearer authentication
To provide authentication data along with SignalR requests, use the AccessTokenProvider option (accessTokenFactory in JavaScript) to specify a function that returns the desired access token. In the .NET Client, this access token is passed in as an HTTP "Bearer Authentication" token (Using the Authorization header with a type of Bearer). In the JavaScript client, the access token is used as a Bearer token, except in a few cases where browser APIs restrict the ability to apply headers (specifically, in Server-Sent Events and WebSockets requests). In these cases, the access token is provided as a query string value access_token.
In the .NET client, the AccessTokenProvider option can be specified using the options delegate in WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.AccessTokenProvider = async () => {
// Get and return the access token.
};
})
.Build();
In the JavaScript client, the access token is configured by setting the accessTokenFactory field on the options object in withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
accessTokenFactory: () => {
// Get and return the access token.
// This function can return a JavaScript Promise if asynchronous
// logic is required to retrieve the access token.
}
})
.build();
In the SignalR Java client, you can configure a bearer token to use for authentication by providing an access token factory to the HttpHubConnectionBuilder. Use withAccessTokenFactory to provide an RxJava Single<String>. With a call to Single.defer, you can write logic to produce access tokens for your client.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withAccessTokenProvider(Single.defer(() -> {
// Your logic here.
return Single.just("An Access Token");
})).build();
Configure timeout and keep-alive options
Additional options for configuring timeout and keep-alive behavior are available on the HubConnection object itself:
| Option | Default value | Description |
|---|---|---|
ServerTimeout |
30 seconds (30,000 milliseconds) | Timeout for server activity. If the server hasn't sent a message in this interval, the client considers the server disconnected and triggers the Closed event (onclose in JavaScript). This value must be large enough for a ping message to be sent from the server and received by the client within the timeout interval. The recommended value is a number at least double the server's KeepAliveInterval value to allow time for pings to arrive. |
HandshakeTimeout |
15 seconds | Timeout for initial server handshake. If the server doesn't send a handshake response in this interval, the client cancels the handshake and triggers the Closed event (onclose in JavaScript). This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | Determines the interval at which the client sends ping messages. Sending any message from the client resets the timer to the start of the interval. If the client hasn't sent a message in the ClientTimeoutInterval set on the server, the server considers the client disconnected. |
In the .NET Client, timeout values are specified as TimeSpan values.
Configure additional options
Additional options can be configured in the WithUrl (withUrl in JavaScript) method on HubConnectionBuilder or on the various configuration APIs on the HttpHubConnectionBuilder in the Java client:
| .NET Option | Default value | Description |
|---|---|---|
AccessTokenProvider |
null |
A function returning a string that is provided as a Bearer authentication token in HTTP requests. |
SkipNegotiation |
false |
Set this to true to skip the negotiation step. Only supported when the WebSockets transport is the only enabled transport. This setting can't be enabled when using the Azure SignalR Service. |
ClientCertificates |
Empty | A collection of TLS certificates to send to authenticate requests. |
Cookies |
Empty | A collection of HTTP cookies to send with every HTTP request. |
Credentials |
Empty | Credentials to send with every HTTP request. |
CloseTimeout |
5 seconds | WebSockets only. The maximum amount of time the client waits after closing for the server to acknowledge the close request. If the server doesn't acknowledge the close within this time, the client disconnects. |
Headers |
Empty | A Map of additional HTTP headers to send with every HTTP request. |
HttpMessageHandlerFactory |
null |
A delegate that can be used to configure or replace the HttpMessageHandler used to send HTTP requests. Not used for WebSocket connections. This delegate must return a non-null value, and it receives the default value as a parameter. Either modify settings on that default value and return it, or return a new HttpMessageHandler instance. When replacing the handler make sure to copy the settings you want to keep from the provided handler, otherwise, the configured options (such as Cookies and Headers) won't apply to the new handler. |
Proxy |
null |
An HTTP proxy to use when sending HTTP requests. |
UseDefaultCredentials |
false |
Set this boolean to send the default credentials for HTTP and WebSockets requests. This enables the use of Windows authentication. |
WebSocketConfiguration |
null |
A delegate that can be used to configure additional WebSocket options. Receives an instance of ClientWebSocketOptions that can be used to configure the options. |
ApplicationMaxBufferSize |
1 MB | The maximum number of bytes received from the server that the client buffers before applying backpressure. Increasing this value allows the client to receive larger messages faster without applying backpressure, but can increase memory consumption. |
TransportMaxBufferSize |
1 MB | The maximum number of bytes sent by the user application that the client buffers before observing backpressure. Increasing this value allows the client to buffer larger messages faster without awaiting backpressure, but can increase memory consumption. |
In the .NET Client, these options can be modified by the options delegate provided to WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.Headers["Foo"] = "Bar";
options.SkipNegotiation = true;
options.Transports = HttpTransportType.WebSockets;
options.Cookies.Add(new Cookie(/* ... */);
options.ClientCertificates.Add(/* ... */);
})
.Build();
In the JavaScript Client, these options can be provided in a JavaScript object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
// "Foo: Bar" will not be sent with WebSockets or Server-Sent Events requests
headers: { "Foo": "Bar" },
transport: signalR.HttpTransportType.LongPolling
})
.build();
In the Java client, these options can be configured with the methods on the HttpHubConnectionBuilder returned from the HubConnectionBuilder.create("HUB URL")
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withHeader("Foo", "Bar")
.shouldSkipNegotiate(true)
.withHandshakeResponseTimeout(30*1000)
.build();
Additional resources
JSON/MessagePack serialization options
ASP.NET Core SignalR supports two protocols for encoding messages: JSON and MessagePack. Each protocol has serialization configuration options.
JSON serialization can be configured on the server using the AddJsonProtocol extension method. AddJsonProtocol can be added after AddSignalR in Startup.ConfigureServices. The AddJsonProtocol method takes a delegate that receives an options object. The PayloadSerializerOptions property on that object is a System.Text.Json JsonSerializerOptions object that can be used to configure serialization of arguments and return values. For more information, see the System.Text.Json documentation.
For example, to configure the serializer to not change the casing of property names, rather than the default camel case names, use the following code in Program.cs:
builder.Services.AddSignalR()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
});
In the .NET client, the same AddJsonProtocol extension method exists on HubConnectionBuilder. The Microsoft.Extensions.DependencyInjection namespace must be imported to resolve the extension method:
// At the top of the file:
using Microsoft.Extensions.DependencyInjection;
// When constructing your connection:
var connection = new HubConnectionBuilder()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
})
.Build();
Note
It's not possible to configure JSON serialization in the JavaScript client at this time.
Switch to Newtonsoft.Json
If you need features of Newtonsoft.Json that aren't supported in System.Text.Json, see Switch to Newtonsoft.Json.
MessagePack serialization options
MessagePack serialization can be configured by providing a delegate to the AddMessagePackProtocol call. See MessagePack in SignalR for more details.
Note
It's not possible to configure MessagePack serialization in the JavaScript client at this time.
Configure server options
The following table describes options for configuring SignalR hubs:
| Option | Default Value | Description |
|---|---|---|
ClientTimeoutInterval |
30 seconds | The server considers the client disconnected if it hasn't received a message (including keep-alive) in this interval. It could take longer than this timeout interval for the client to be marked disconnected due to how this is implemented. The recommended value is double the KeepAliveInterval value. |
HandshakeTimeout |
15 seconds | If the client doesn't send an initial handshake message within this time interval, the connection is closed. This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | If the server hasn't sent a message within this interval, a ping message is sent automatically to keep the connection open. When changing KeepAliveInterval, change the ServerTimeout or serverTimeoutInMilliseconds setting on the client. The recommended ServerTimeout or serverTimeoutInMilliseconds value is double the KeepAliveInterval value. |
SupportedProtocols |
All installed protocols | Protocols supported by this hub. By default, all protocols registered on the server are allowed. Protocols can be removed from this list to disable specific protocols for individual hubs. |
EnableDetailedErrors |
false |
If true, detailed exception messages are returned to clients when an exception is thrown in a Hub method. The default is false because these exception messages can contain sensitive information. |
StreamBufferCapacity |
10 |
The maximum number of items that can be buffered for client upload streams. If this limit is reached, the processing of invocations is blocked until the server processes stream items. |
MaximumReceiveMessageSize |
32 KB | Maximum size of a single incoming hub message. Increasing the value may increase the risk of Denial of service (DoS) attacks. |
MaximumParallelInvocationsPerClient |
1 | The maximum number of hub methods that each client can call in parallel before queueing. |
DisableImplicitFromServicesParameters |
false |
Hub method arguments will be resolved from DI if possible. |
Options can be configured for all hubs by providing an options delegate to the AddSignalR call in Program.cs.
builder.Services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(1);
});
Options for a single hub override the global options provided in AddSignalR and can be configured using AddHubOptions:
builder.Services.AddSignalR().AddHubOptions<ChatHub>(options =>
{
options.EnableDetailedErrors = true;
});
Advanced HTTP configuration options
Use HttpConnectionDispatcherOptions to configure advanced settings related to transports and memory buffer management. These options are configured by passing a delegate to MapHub in Program.cs.
using Microsoft.AspNetCore.Http.Connections;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddSignalR();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.MapHub<ChatHub>("/chathub", options =>
{
options.Transports =
HttpTransportType.WebSockets |
HttpTransportType.LongPolling;
}
);
app.Run();
The following table describes options for configuring ASP.NET Core SignalR's advanced HTTP options:
| Option | Default Value | Description |
|---|---|---|
ApplicationMaxBufferSize |
64 KB | The maximum number of bytes received from the client that the server buffers before applying backpressure. Increasing this value allows the server to receive larger messages faster without applying backpressure, but can increase memory consumption. |
TransportMaxBufferSize |
64 KB | The maximum number of bytes sent by the app that the server buffers before observing backpressure. Increasing this value allows the server to buffer larger messages faster without awaiting backpressure, but can increase memory consumption. |
AuthorizationData |
Data automatically gathered from the Authorize attributes applied to the Hub class. |
A list of IAuthorizeData objects used to determine if a client is authorized to connect to the hub. |
Transports |
All Transports are enabled. | A bit flags enum of HttpTransportType values that can restrict the transports a client can use to connect. |
LongPolling |
See below. | Additional options specific to the Long Polling transport. |
WebSockets |
See below. | Additional options specific to the WebSockets transport. |
MinimumProtocolVersion |
0 | Specify the minimum version of the negotiate protocol. This is used to limit clients to newer versions. |
CloseOnAuthenticationExpiration |
false | Set this option to enable authentication expiration tracking which will close connections when a token expires. |
The Long Polling transport has additional options that can be configured using the LongPolling property:
| Option | Default Value | Description |
|---|---|---|
PollTimeout |
90 seconds | The maximum amount of time the server waits for a message to send to the client before terminating a single poll request. Decreasing this value causes the client to issue new poll requests more frequently. |
The WebSocket transport has additional options that can be configured using the WebSockets property:
| Option | Default Value | Description |
|---|---|---|
CloseTimeout |
5 seconds | After the server closes, if the client fails to close within this time interval, the connection is terminated. |
SubProtocolSelector |
null |
A delegate that can be used to set the Sec-WebSocket-Protocol header to a custom value. The delegate receives the values requested by the client as input and is expected to return the desired value. |
Configure client options
Client options can be configured on the HubConnectionBuilder type (available in the .NET and JavaScript clients). It's also available in the Java client, but the HttpHubConnectionBuilder subclass is what contains the builder configuration options, as well as on the HubConnection itself.
Configure logging
Logging is configured in the .NET Client using the ConfigureLogging method. Logging providers and filters can be registered in the same way as they are on the server. See the Logging in ASP.NET Core documentation for more information.
Note
In order to register Logging providers, you must install the necessary packages. See the Built-in logging providers section of the docs for a full list.
For example, to enable Console logging, install the Microsoft.Extensions.Logging.Console NuGet package. Call the AddConsole extension method:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub")
.ConfigureLogging(logging => {
logging.SetMinimumLevel(LogLevel.Information);
logging.AddConsole();
})
.Build();
In the JavaScript client, a similar configureLogging method exists. Provide a LogLevel value indicating the minimum level of log messages to produce. Logs are written to the browser console window.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging(signalR.LogLevel.Information)
.build();
Instead of a LogLevel value, you can also provide a string value representing a log level name. This is useful when configuring SignalR logging in environments where you don't have access to the LogLevel constants.
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging("warn")
.build();
The following table lists the available log levels. The value you provide to configureLogging sets the minimum log level that will be logged. Messages logged at this level, or the levels listed after it in the table, will be logged.
| String | LogLevel |
|---|---|
trace |
LogLevel.Trace |
debug |
LogLevel.Debug |
info or information |
LogLevel.Information |
warn or warning |
LogLevel.Warning |
error |
LogLevel.Error |
critical |
LogLevel.Critical |
none |
LogLevel.None |
Note
To disable logging entirely, specify signalR.LogLevel.None in the configureLogging method.
For more information on logging, see the SignalR Diagnostics documentation.
The SignalR Java client uses the SLF4J library for logging. It's a high-level logging API that allows users of the library to choose their own specific logging implementation by bringing in a specific logging dependency. The following code snippet shows how to use java.util.logging with the SignalR Java client.
implementation 'org.slf4j:slf4j-jdk14:1.7.25'
If you don't configure logging in your dependencies, SLF4J loads a default no-operation logger with the following warning message:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
This can safely be ignored.
Configure allowed transports
The transports used by SignalR can be configured in the WithUrl call (withUrl in JavaScript). A bitwise-OR of the values of HttpTransportType can be used to restrict the client to only use the specified transports. All transports are enabled by default.
For example, to disable the Server-Sent Events transport, but allow WebSockets and Long Polling connections:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", HttpTransportType.WebSockets | HttpTransportType.LongPolling)
.Build();
In the JavaScript client, transports are configured by setting the transport field on the options object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", { transport: signalR.HttpTransportType.WebSockets | signalR.HttpTransportType.LongPolling })
.build();
In this version of the Java client WebSockets is the only available transport.
In the Java client, the transport is selected with the withTransport method on the HttpHubConnectionBuilder. The Java client defaults to using the WebSockets transport.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withTransport(TransportEnum.WEBSOCKETS)
.build();
Note
The SignalR Java client doesn't support transport fallback yet.
Configure bearer authentication
To provide authentication data along with SignalR requests, use the AccessTokenProvider option (accessTokenFactory in JavaScript) to specify a function that returns the desired access token. In the .NET Client, this access token is passed in as an HTTP "Bearer Authentication" token (Using the Authorization header with a type of Bearer). In the JavaScript client, the access token is used as a Bearer token, except in a few cases where browser APIs restrict the ability to apply headers (specifically, in Server-Sent Events and WebSockets requests). In these cases, the access token is provided as a query string value access_token.
In the .NET client, the AccessTokenProvider option can be specified using the options delegate in WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.AccessTokenProvider = async () => {
// Get and return the access token.
};
})
.Build();
In the JavaScript client, the access token is configured by setting the accessTokenFactory field on the options object in withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
accessTokenFactory: () => {
// Get and return the access token.
// This function can return a JavaScript Promise if asynchronous
// logic is required to retrieve the access token.
}
})
.build();
In the SignalR Java client, you can configure a bearer token to use for authentication by providing an access token factory to the HttpHubConnectionBuilder. Use withAccessTokenFactory to provide an RxJava Single<String>. With a call to Single.defer, you can write logic to produce access tokens for your client.
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withAccessTokenProvider(Single.defer(() -> {
// Your logic here.
return Single.just("An Access Token");
})).build();
Configure timeout and keep-alive options
Additional options for configuring timeout and keep-alive behavior are available on the HubConnection object itself:
| Option | Default value | Description |
|---|---|---|
ServerTimeout |
30 seconds (30,000 milliseconds) | Timeout for server activity. If the server hasn't sent a message in this interval, the client considers the server disconnected and triggers the Closed event (onclose in JavaScript). This value must be large enough for a ping message to be sent from the server and received by the client within the timeout interval. The recommended value is a number at least double the server's KeepAliveInterval value to allow time for pings to arrive. |
HandshakeTimeout |
15 seconds | Timeout for initial server handshake. If the server doesn't send a handshake response in this interval, the client cancels the handshake and triggers the Closed event (onclose in JavaScript). This is an advanced setting that should only be modified if handshake timeout errors are occurring due to severe network latency. For more detail on the handshake process, see the SignalR Hub Protocol Specification. |
KeepAliveInterval |
15 seconds | Determines the interval at which the client sends ping messages. Sending any message from the client resets the timer to the start of the interval. If the client hasn't sent a message in the ClientTimeoutInterval set on the server, the server considers the client disconnected. |
In the .NET Client, timeout values are specified as TimeSpan values.
Configure additional options
Additional options can be configured in the WithUrl (withUrl in JavaScript) method on HubConnectionBuilder or on the various configuration APIs on the HttpHubConnectionBuilder in the Java client:
| .NET Option | Default value | Description |
|---|---|---|
AccessTokenProvider |
null |
A function returning a string that is provided as a Bearer authentication token in HTTP requests. |
SkipNegotiation |
false |
Set this to true to skip the negotiation step. Only supported when the WebSockets transport is the only enabled transport. This setting can't be enabled when using the Azure SignalR Service. |
ClientCertificates |
Empty | A collection of TLS certificates to send to authenticate requests. |
Cookies |
Empty | A collection of HTTP cookies to send with every HTTP request. |
Credentials |
Empty | Credentials to send with every HTTP request. |
CloseTimeout |
5 seconds | WebSockets only. The maximum amount of time the client waits after closing for the server to acknowledge the close request. If the server doesn't acknowledge the close within this time, the client disconnects. |
Headers |
Empty | A Map of additional HTTP headers to send with every HTTP request. |
HttpMessageHandlerFactory |
null |
A delegate that can be used to configure or replace the HttpMessageHandler used to send HTTP requests. Not used for WebSocket connections. This delegate must return a non-null value, and it receives the default value as a parameter. Either modify settings on that default value and return it, or return a new HttpMessageHandler instance. When replacing the handler make sure to copy the settings you want to keep from the provided handler, otherwise, the configured options (such as Cookies and Headers) won't apply to the new handler. |
Proxy |
null |
An HTTP proxy to use when sending HTTP requests. |
UseDefaultCredentials |
false |
Set this boolean to send the default credentials for HTTP and WebSockets requests. This enables the use of Windows authentication. |
WebSocketConfiguration |
null |
A delegate that can be used to configure additional WebSocket options. Receives an instance of ClientWebSocketOptions that can be used to configure the options. |
ApplicationMaxBufferSize |
1 MB | The maximum number of bytes received from the server that the client buffers before applying backpressure. Increasing this value allows the client to receive larger messages faster without applying backpressure, but can increase memory consumption. |
TransportMaxBufferSize |
1 MB | The maximum number of bytes sent by the user application that the client buffers before observing backpressure. Increasing this value allows the client to buffer larger messages faster without awaiting backpressure, but can increase memory consumption. |
In the .NET Client, these options can be modified by the options delegate provided to WithUrl:
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/chathub", options => {
options.Headers["Foo"] = "Bar";
options.SkipNegotiation = true;
options.Transports = HttpTransportType.WebSockets;
options.Cookies.Add(new Cookie(/* ... */);
options.ClientCertificates.Add(/* ... */);
})
.Build();
In the JavaScript Client, these options can be provided in a JavaScript object provided to withUrl:
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
// "Foo: Bar" will not be sent with WebSockets or Server-Sent Events requests
headers: { "Foo": "Bar" },
transport: signalR.HttpTransportType.LongPolling
})
.build();
In the Java client, these options can be configured with the methods on the HttpHubConnectionBuilder returned from the HubConnectionBuilder.create("HUB URL")
HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/chathub")
.withHeader("Foo", "Bar")
.shouldSkipNegotiate(true)
.withHandshakeResponseTimeout(30*1000)
.build();
Additional resources
ASP.NET Core