Nguon: Microsoft Learn · .NET 8.0
Cấu hình ASP.NET Core SignalR
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ọn | Mặc định | Mô tả |
|---|---|---|
ClientTimeoutInterval | 30 giây | Server coi client đã ngắt kết nối nếu không nhận được tin nhắn |
HandshakeTimeout | 15 giây | Thời gian cho phép handshake (bắt tay) ban đầu |
KeepAliveInterval | 15 giây | Khoảng thời gian gửi ping tự động |
EnableDetailedErrors | false | Trả về thông báo exception chi tiết cho client |
StreamBufferCapacity | 10 | Số phần tử tối đa được đệm cho client upload streams |
MaximumReceiveMessageSize | 32 KB | Kích thước tối đa của một tin nhắn đến |
MaximumParallelInvocationsPerClient | 1 | Số 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ọn | Mặc định | Mô tả |
|---|---|---|
ApplicationMaxBufferSize | 64 KB | Số byte tối đa từ client trước khi áp backpressure |
TransportMaxBufferSize | 64 KB | Số byte tối đa được gửi trước khi áp backpressure |
Transports | Tất cả | Giới hạn các transport được phép |
LongPolling.PollTimeout | 90 giây | Thời gian chờ tối đa cho một tin nhắn |
WebSockets.CloseTimeout | 5 giây | Timeout đó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ọn | Mặc định | Mô tả |
|---|---|---|
WithServerTimeout | 30 giây | Timeout cho hoạt động của server |
WithKeepAliveInterval | 15 giây | Khoảng thời gian gửi ping |
HandshakeTimeout | 15 giây | Timeout 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:
AccessTokenProvider— Hàm cung cấp Bearer tokenSkipNegotiation— Bỏ qua bước negotiation (chỉ áp dụng cho WebSockets)Headers— HTTP headers tùy chỉnhCookies— HTTP cookiesCredentials— Thông tin xác thực requestCloseTimeout— Timeout đóng WebSocketProxy— Cài đặt HTTP proxyUseDefaultCredentials— Xác thực Windows