【发布时间】:2020-07-09 13:55:36
【问题描述】:
我已经使用 signalR 制作了 .NET Core API,当我使用 https 协议加载应用程序时,我可以连接到 signalR javascript 客户端,但是当我使用 http 协议加载应用程序时 - signalR js 客户端无法连接到集线器。 CORS 工作正常。
我的代码: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();
});
}
在我的 JS 应用上:
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);
});
【问题讨论】:
-
您收到的错误信息是什么? “正常”http请求是否有效?也许你没有打开 http 端口或使用 https 端口并尝试通过 http 连接到它?
-
我没有收到任何错误,但连接没有打开。 http 一切正常,我不是在 prod 中启动我的后端应用程序,而是在 Visual Studio 的开发模式下启动
标签: asp.net-core signalr asp.net-core-signalr