【发布时间】:2020-01-15 10:03:28
【问题描述】:
我有一个在 http://localhost:5002 本地运行的 .NET Core 2.2 服务器和一个在 http://localhost:5000 上运行的客户端(主要是从 Microsoft's docs 复制/粘贴)。
在服务器端,我有文档中的示例集线器,刚刚重命名为 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 配置能够处理它。
【问题讨论】:
-
在您的
CORS配置中添加.SetIsOriginAllowed((host) => true)); -
@Kiril1512 不幸的是它并没有改变任何东西。似乎服务器永远不会返回
Access-Control-Allow-Origin标头。
标签: c# asp.net-core signalr asp.net-core-2.2