我有一个在http://localhost:5002
上本地运行的.NET Core 2.2服务器,以及一个在Microsoft's docs上运行的客户端(主要是从http://localhost:5000
复制/粘贴的客户端。
在服务器端,我有来自文档的示例中心,刚刚重命名为TestHub
,并且在Startup.cs
中包含以下位:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSignalR(options => { options.EnableDetailedErrors = true; });
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app)
{
...
app.UsePathBase("/custom");
app.UseSignalR(routes =>
{
routes.MapHub<TestHub>("/test");
});
app.UseCors(options => options
.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("http://localhost:5000")
.AllowCredentials());
app.UseMvc();
}
[CORS配置改编自this GitHub issue。
在客户端,我按照文档中的说明安装了@microsoft/signalr
程序包,然后略微更改了chat.js
文件以使用服务器的URL。
"use strict";
// This is the only line I changed
var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:5002/test").build();
//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;
connection.on("ReceiveMessage", function (user, message) {
...
});
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
...
});
我尝试了http://localhost:5002/test
和http://localhost:5002/custom/test
,但没有任何效果。 Chrome仅说net::ERR_FAILED
,而Firefox则报告对405
的OPTIONS
调用为http://localhost:5002/test/negotiate?negotiateVersion=1
响应。但是,两个浏览器都警告说不存在Access-Control-Allow-Origin
标头,这很奇怪,因为我希望CORS配置能够处理它。
最后,我在管道(例如AddSignalR
)中设置了CORS配置在所有其他中间件之前],并且终于成功了。
public void Configure(IApplicationBuilder app)
{
app.UseCors(...);
// Everything else
}
尝试从您的ConfigureServices方法中尝试使用AddCors和Addpolicy。这为我解决了问题。