I have problem with SignalR WebSocket on ASP.NET Core API that is hosted on kestrel.
Full log from console (browser-Chrome)
[2023-01-11T09:05:21.250Z] Debug: Starting HubConnection. signalr.js:457 [2023-01-11T09:05:21.251Z] Debug: Starting connection with transfer format 'Text'. signalr.js:457 [2023-01-11T09:05:21.252Z] Debug: Sending negotiation request: https://localhost:60001/PushMessagesHub/negotiate?negotiateVersion=1. signalr.js:457 [2023-01-11T09:05:21.624Z] Debug: Selecting transport 'WebSockets'. signalr.js:457 [2023-01-11T09:05:21.624Z] Trace: (WebSockets transport) Connecting. signalr.js:2287 WebSocket connection to 'wss://localhost:60001/PushMessagesHub?id=srqV9jQe1zpE5cuTdzzcdg&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJGQ01fVG9rZW4iOiJGQ01fVE9LRU5fRk9SX0NMSUVOVF9BUFBfUkVHSVNUUkFUSU9OIiwiQXBwbGljYXRpb25JZCI6ImZkMmIwNmE5LTA4YmItNDRkMy04MDQxLWUxYTMyOGVkZTk5ZCIsImV4cCI6MTY3Njg4MzkyMCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdC8iLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0LyJ9.ojHw8RS_ZoB0S8w8nlqnfY4uIsit1yrj8iCBURvf2Hw' failed: (anonymous) @ signalr.js:2287 signalr.js:453 [2023-01-11T09:05:22.027Z] Information: (WebSockets transport) There was an error with the transport. signalr.js:447 [2023-01-11T09:05:22.027Z] Error: Failed to start the transport 'WebSockets': Error: WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled. log @ signalr.js:447 signalr.js:457 [2023-01-11T09:05:22.027Z] Debug: Selecting transport 'ServerSentEvents'. signalr.js:457 [2023-01-11T09:05:22.027Z] Debug: Sending negotiation request: https://localhost:60001/PushMessagesHub/negotiate?negotiateVersion=1. signalr.js:457 [2023-01-11T09:05:22.040Z] Trace: (SSE transport) Connecting. :60001/PushMessagesHub?id=2orOj_0FgQIqosu2phE-ow&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJGQ01fVG9rZW4iOiJGQ01fVE9LRU5fRk9SX0NMSUVOVF9BUFBfUkVHSVNUUkFUSU9OIiwiQXBwbGljYXRpb25JZCI6ImZkMmIwNmE5LTA4YmItNDRkMy04MDQxLWUxYTMyOGVkZTk5ZCIsImV4cCI6MTY3Njg4MzkyMCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdC8iLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0LyJ9.ojHw8RS_ZoB0S8w8nlqnfY4uIsit1yrj8iCBURvf2Hw:1 Failed to load resource: the server responded with a status of 401 () signalr.js:447 [2023-01-11T09:05:22.045Z] Error: Failed to start the transport 'ServerSentEvents': Error: EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled. log @ signalr.js:447 signalr.js:457 [2023-01-11T09:05:22.045Z] Debug: Selecting transport 'LongPolling'. signalr.js:457 [2023-01-11T09:05:22.046Z] Debug: Sending negotiation request: https://localhost:60001/PushMessagesHub/negotiate?negotiateVersion=1. signalr.js:457 [2023-01-11T09:05:22.055Z] Trace: (LongPolling transport) Connecting. signalr.js:457 [2023-01-11T09:05:22.055Z] Trace: (LongPolling transport) polling: https://localhost:60001/PushMessagesHub?id=k2D5mBMDsZtgjLEbRY2MRg&*=1673427922055. signalr.js:457 [2023-01-11T09:05:22.077Z] Trace: (LongPolling transport) polling: https://localhost:60001/PushMessagesHub?id=k2D5mBMDsZtgjLEbRY2MRg&*=1673427922077. signalr.js:457 [2023-01-11T09:05:22.077Z] Debug: The HttpConnection connected successfully. signalr.js:457 [2023-01-11T09:05:22.077Z] Debug: Sending handshake request. signalr.js:457 [2023-01-11T09:05:22.078Z] Trace: (LongPolling transport) sending data. String data of length 32. signalr.js:457 [2023-01-11T09:05:22.095Z] Trace: (LongPolling transport) request complete. Response status: 200. signalr.js:453 [2023-01-11T09:05:22.095Z] Information: Using HubProtocol 'json'. signalr.js:457 [2023-01-11T09:05:22.101Z] Trace: (LongPolling transport) data received. String data of length 3. signalr.js:457 [2023-01-11T09:05:22.102Z] Debug: Server handshake complete. signalr.js:457 [2023-01-11T09:05:22.102Z] Trace: (LongPolling transport) polling: https://localhost:60001/PushMessagesHub?id=k2D5mBMDsZtgjLEbRY2MRg&_=1673427922102. signalr.js:457 [2023-01-11T09:05:22.102Z] Debug: HubConnection connected successfully. site.js?v=B8WTYmxlo2Bbl0nfTLXLzSFGgNFHTS36I85-T8V3fOA:54 SignalR Connected.
Startup.cs (API)
public void ConfigureServices(IServiceCollection services)
{
DependencyInjection.ConfigureDIServices(services, Configuration);
AuthConfig.ConfigureAuth(services, Configuration);
services.AddSignalR(o =>
{
o.EnableDetailedErrors = true;
});
SwaggerConfig.ConfigureSwagger(services);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddControllers();
services.AddControllersWithViews();
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed((host) => true)
.AllowCredentials();
}));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime, ILogger<Startup> logger)
{
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors("CorsPolicy");
app.UseRouting();
app.UseWebSockets();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<PushMessagesHub>("/PushMessagesHub");
});
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Swagger_Custom_index.html");
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
});
}
signalr_client.js (MVC app)
const connection = new signalR.HubConnectionBuilder()
.withUrl("https://localhost:60001/PushMessagesHub", {
//skipNegotiation: false,
//transport: signalR.HttpTransportType.WebSockets,
//withCredentials: false,
accessTokenFactory: () => {
var bearerToken = $('#bearer_span').text();
return bearerToken;
}
})
.build();
connection.onclose(async () => {
await start();
});
connection.on("PreviewImagesStreamStartedNotification", (deviceId) => {
//StartDownloadingPreviewImagesStream(deviceId);
});
connection.on("PreviewImagesStreamStoppedNotification", (deviceId) => {
//_PreviewStreamCancellationTokenSource.Cancel();
});
start();
async function start() {
try {
await connection.start();
console.log("SignalR Connected.");
} catch (err) {
console.log(err);
setTimeout(start, 5000);
}
};
Update 11.01.2023.
Added full log from console (browser).
WebSocket works normally when connecting to SignalR Hub from backend code of ASP.NET Core MVC app, but it does not work when connecting from browser(JS/jQuery). At the end of full console log you can see that SignalR connects to hub but protocol falls to LoongPooling.
1条答案
按热度按时间cgyqldqp1#
问题是由于浏览器限制使用JWT与WebSockets/ServerSentEvents。
此问题的解决方案位于Microsoft SignalR文档页面:
问题解决方案