Reputation: 51
I've made .NET Core API with signalR, when I load app with https protocol, I can connect with signalR javascript client, but when I load app with http protocol - signalR js client can't connect to hub. CORS works fine.
My Code: Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader());
});
services.AddSignalR(options =>
{
options.EnableDetailedErrors = true;
});
services.AddControllers(options =>
{
options.EnableEndpointRouting = true;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
logger.LogInformation($"Started Configure with is Production mode:{env.IsProduction()}");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(route =>
{
route.MapHub<ConnectionHub>("/chat");
route.MapControllers();
});
}
On my JS app:
var connection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:5066/chat") // WHEN I'M CHANGING TO HTTPS host - everything works fine
.build();
// Create a function that the hub can call to broadcast messages.
connection.on("broadcastMessage", function (name, message) { });
connection.start()
.then(function () {
connection.invoke("Send", name, messageInput.value);
})
.catch((error) => {
console.error(error.message);
});
Upvotes: 1
Views: 3207
Reputation: 51
Well , I resolved this problem adding options object to signalR client (add skipNegotiations: true) . To be honestly I hdont know what does it mean yet (tomorrow I'll read meaning and I'll write description of this property).
// Start the connection.
var connection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:5066/chat", {
skipNegotiation: false,
transport: signalR.HttpTransportType.WebSockets|
signalR.HttpTransportType.LongPolling |
signalR.HttpTransportType.serverSentEvents,
})
.build();
UPD: Well, It became works thanks to adding options object after url string. About this object. At first signalR make negotiation (it's like some handshake between back and front) and if transport type is only websockets - you should skip it.
Upvotes: 4