Nguon: Microsoft Learn · .NET 8.0

Cấu hình ASP.NET Core SignalR

Nguồn: ASP.NET Core SignalR Configuration

Bài viết này bao gồm hướng dẫn cấu hình ASP.NET Core SignalR cho cả ứng dụng client và server.

1. Cấu hình Serialization (tuần tự hóa)

JSON Serialization

Cấu hình JSON protocol serialization bằng AddJsonProtocol:

csharp
builder.Services.AddSignalR()
    .AddJsonProtocol(options => {
        options.PayloadSerializerOptions.PropertyNamingPolicy = null;
    });

Trên .NET client:

csharp
var connection = new HubConnectionBuilder()
    .AddJsonProtocol(options => {
        options.PayloadSerializerOptions.PropertyNamingPolicy = null;
    })
    .Build();

MessagePack Serialization

Cấu hình bằng phương thức mở rộng AddMessagePackProtocol.

2. Tùy chọn Server

Tùy chọnMặc địnhMô tả
ClientTimeoutInterval30 giâyServer coi client đã ngắt kết nối nếu không nhận được tin nhắn
HandshakeTimeout15 giâyThời gian cho phép handshake (bắt tay) ban đầu
KeepAliveInterval15 giâyKhoảng thời gian gửi ping tự động
EnableDetailedErrorsfalseTrả về thông báo exception chi tiết cho client
StreamBufferCapacity10Số phần tử tối đa được đệm cho client upload streams
MaximumReceiveMessageSize32 KBKích thước tối đa của một tin nhắn đến
MaximumParallelInvocationsPerClient1Số lần gọi hub method song song tối đa mỗi client

Cấu hình toàn cục trong Program.cs:

csharp
builder.Services.AddSignalR(hubOptions =>
{
    hubOptions.EnableDetailedErrors = true;
    hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(1);
});

Cấu hình cho hub cụ thể:

csharp
builder.Services.AddSignalR().AddHubOptions<ChatHub>(options =>
{
    options.EnableDetailedErrors = true;
});

3. Tùy chọn HTTP nâng cao

Cấu hình bằng MapHub:

csharp
app.MapHub<ChatHub>("/chathub", options =>
{
    options.Transports =
        HttpTransportType.WebSockets |
        HttpTransportType.LongPolling;
});
Tùy chọnMặc địnhMô tả
ApplicationMaxBufferSize64 KBSố byte tối đa từ client trước khi áp backpressure
TransportMaxBufferSize64 KBSố byte tối đa được gửi trước khi áp backpressure
TransportsTất cảGiới hạn các transport được phép
LongPolling.PollTimeout90 giâyThời gian chờ tối đa cho một tin nhắn
WebSockets.CloseTimeout5 giâyTimeout đóng kết nối WebSocket

4. Cấu hình Client

Logging (.NET)

csharp
var connection = new HubConnectionBuilder()
    .WithUrl("https://example.com/chathub")
    .ConfigureLogging(logging => {
        logging.SetMinimumLevel(LogLevel.Information);
        logging.AddConsole();
    })
    .Build();

Logging (JavaScript)

javascript
let connection = new signalR.HubConnectionBuilder()
    .withUrl("/chathub")
    .configureLogging(signalR.LogLevel.Information)
    .build();

Cấu hình Transports

csharp
var connection = new HubConnectionBuilder()
    .WithUrl("https://example.com/chathub", 
        HttpTransportType.WebSockets | HttpTransportType.LongPolling)
    .Build();

Xác thực Bearer (.NET)

csharp
var connection = new HubConnectionBuilder()
    .WithUrl("https://example.com/chathub", options => {
        options.AccessTokenProvider = async () => {
            // Lấy và trả về access token
        };
    })
    .Build();

Xác thực Bearer (JavaScript)

javascript
let connection = new signalR.HubConnectionBuilder()
    .withUrl("/chathub", {
        accessTokenFactory: () => {
            // Lấy và trả về access token
        }
    })
    .build();

5. Tùy chọn Timeout và Keep-Alive

.NET Client

csharp
var builder = new HubConnectionBuilder()
    .WithUrl(Navigation.ToAbsoluteUri("/chathub"))
    .WithServerTimeout(TimeSpan.FromSeconds(60))
    .WithKeepAliveInterval(TimeSpan.FromSeconds(30))
    .Build();
Tùy chọnMặc địnhMô tả
WithServerTimeout30 giâyTimeout cho hoạt động của server
WithKeepAliveInterval15 giâyKhoảng thời gian gửi ping
HandshakeTimeout15 giâyTimeout handshake ban đầu

JavaScript Client

javascript
var connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub")
    .withServerTimeout(60000)
    .withKeepAliveInterval(30000)
    .build();

6. Stateful Reconnect (Kết nối lại có trạng thái - ASP.NET Core 8+)

Bật trên server:

csharp
app.MapHub<MyHub>("/hubName", options =>
{
    options.AllowStatefulReconnects = true;
    options.StatefulReconnectBufferSize = 1000; // Tùy chọn
});

Bật trên JavaScript client:

javascript
const builder = new signalR.HubConnectionBuilder()
    .withUrl("/hubname")
    .withStatefulReconnect({ bufferSize: 1000 });

Bật trên .NET client:

csharp
var builder = new HubConnectionBuilder()
    .WithUrl("<hub url>")
    .WithStatefulReconnect();
builder.Services.Configure<HubConnectionOptions>(
    o => o.StatefulReconnectBufferSize = 1000);

7. Các tùy chọn Client bổ sung

Các cấu hình có sẵn bao gồm: