use*_*692 1 c# asp.net cors signalr
我目前正在学习这个基本信号 R 教程。但因为我想在现有项目中使用它,所以我将其分开。中心与客户端位于不同的项目内。因此IP地址不同。在 Hub I 的配置中当然启用了 cors:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
services.AddSignalR();
//other configuration code
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
app.UseRouting();
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<LiveUpdating.ChatHub>("/chatHub");
});
}
Run Code Online (Sandbox Code Playgroud)
但是,当我现在尝试连接到客户端中的 chatHub(设置与上面的链接完全相同,只是我将连接更改为var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44316/chatHub").build(); )时,我收到此错误:
Access to fetch at 'https://localhost:44316/chatHub/negotiate?negotiateVersion=1' from
origin 'https://localhost:44341' has been blocked by CORS policy: Response to preflight
request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin'
header in the response must not be the wildcard '*' when the request's credentials mode
is 'include'.
Run Code Online (Sandbox Code Playgroud)
当我添加如上所示的 app.UseCors 时,这通常不应该起作用吗?因为对于我所有其他的休息控制器来说,它工作得很好。
将 app.useCors 替换为
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials());
Run Code Online (Sandbox Code Playgroud)
修复了错误