CORS政策不想与SignalR和ASP.NET Core一起使用

the*_*iak 6 cors signalr asp.net-core angular angular7

我的ASP.NET核心API和Angular Client有问题。我想实现SignalR在API和Angular之间建立连接。cors策略已在我们的客户端和API上激活,因为我们已经可以使用我们的客户端从API检索数据。但是现在的问题是,当我尝试使用SignalR时,收到CORS POLICY错误:

通过CORS策略已阻止从源“ http:// localhost:4200 ” 访问“ http:// localhost:50501 / CoordinatorHub / negotiate ” 处的XMLHttpRequest :对预检请求的响应未通过访问控制检查:否'访问-Control-Allow-Origin'标头出现在请求的资源上。

但是我们的API上的Startup.cs内部已经有cors政策,就像这样:

在ConfigureServices方法中:

services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigin",
        builder => 
        builder.WithOrigins("http://localhost:4200/")
            .AllowCredentials()
            //.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .SetIsOriginAllowedToAllowWildcardSubdomains());
});
Run Code Online (Sandbox Code Playgroud)

在Configure方法中:

app.UseCors("AllowSpecificOrigin");
Run Code Online (Sandbox Code Playgroud)

在我们的客户端中,我们只想尝试在API和客户端之间建立连接,就像这样:

this.hubConnection.start({withCredentials: false}).then(() => 
     this.hubConnection.invoke('send', 'Hello'));
Run Code Online (Sandbox Code Playgroud)

BRA*_*mel 8

请注意,这可以应用于 .net core 3.1

正如它在 microsoft docs 上所说,它似乎不起作用 docs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Preceding code ommitted.
    app.UseRouting();

    app.UseCors();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

    // Following code ommited.
}
Run Code Online (Sandbox Code Playgroud)

警告

对于端点路由,必须将 CORS 中间件配置为在对 UseRouting 和 UseEndpoints 的调用之间执行。不正确的配置将导致中间件停止正常运行。

但是,如果您首先移动 UseCors(),您的应用程序将按预期工作,因此工作代码将是

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
                options.AddDefaultPolicy(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//place your useCors here 
    app.UseCors();
    app.UseRouting();


    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

    // Following code ommited.
}
Run Code Online (Sandbox Code Playgroud)


kul*_*eep 8

接受的答案对我不起作用,所以我决定把对我有用的东西放在这里。万一有人偶然发现同样的问题。

在 Angular 9 上使用 signalR 时,我在本地测试中遇到了同样的问题。

我通过将我的 Asp NET Core (3.1) 应用 URL 从 https 切换到 http 来解决它。如果您使用的是 Visual Studio,

  1. 只需右键单击项目属性-> 调试。
  2. 取消选中启用 SSL

Asp网络核心项目

也不要忘记在 angular App 中更改 URL 上的端口。所以基本上角度应用程序中的 URL 将是这样的

this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl("http://localhost:50782/hub").build();
Run Code Online (Sandbox Code Playgroud)

而配置方法中的相关代码是这样的

app.UseHttpsRedirection();
app.UseStaticFiles();

   
app.UseRouting();
app.UseCors("_myAllowSpecificOrigins");

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapHub<ChatHub>("/hub");
});
Run Code Online (Sandbox Code Playgroud)

在你的 configureServices 方法中,我遵循了

    services.AddRazorPages();

    services.AddCors(options =>
        {
            options.AddPolicy("_myAllowSpecificOrigins",
                builder =>
                {
                    builder.WithOrigins("https://localhost:4200")
                           .AllowAnyHeader()
                           .AllowAnyMethod()
                           .SetIsOriginAllowed((x) => true)
                           .AllowCredentials();
                });
        });
    
   services.AddSignalR();
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 !

更新

如果你只是玩弄你的本地计算机上的样品,你也可以尝试运行安全模式铬提到这里

在我的 Mac 上,我只是简单地从终端运行命令

open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_test" --disable-web-security
Run Code Online (Sandbox Code Playgroud)

有了这个,您应该能够在没有 CORS 打扰的情况下运行您的示例

  • 深入挖掘后我发现的另一个选择是, ```builder .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() .SetIsOriginAllowed(origin =&gt; new Uri(origin).Host == "localhost");` `` (2认同)

Ham*_*uhi 6

我根据这个链接解决了我的问题

将此块代码添加到服务

services.AddCors(options => options.AddPolicy("CorsPolicy",
        builder =>
        {
            builder.AllowAnyHeader()
                   .AllowAnyMethod()
                   .SetIsOriginAllowed((host) => true)
                   .AllowCredentials();
        }));
Run Code Online (Sandbox Code Playgroud)

并在配置应用程序中添加此块代码

app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
        {
            routes.MapHub<General>("/hubs/general");
        });
Run Code Online (Sandbox Code Playgroud)


Sab*_*viş 6

经过大量研究后,我也想分享我所面临的问题以及我如何解决它。

我的场景是;我将我的.Net Core应用程序Azure App ServicesAzure SignalR配置一起部署。当我在本地计算机上运行前端和后端时,一切工作正常。../Hub/negotiate但是当我在 azure 服务上部署我的应用程序时,由于这个问题和 cors 问题,我无法连接。

我是如何修复的;首先确保你已经在你的 api 中启用了 cors 设置,正如朋友在这里指出的那样。我在此链接中从 Microsoft 文档中获取了示例 signalR 应用程序。最后我意识到在项目示例中该@aspnet/signalr@1.0.0包已过时并移至@microsoft/signalr. 在我的研究中,我发现在某些地方withCredentials应该设置为 false,因为默认情况下该值为 true 并强制连接使用 SSL。我的客户端应用程序正在本地使用 http 运行并尝试连接 https 连接。有关更多信息,请参阅此链接。在旧的 signalR npm 包中,这个值没有设置,所以当我切换到新的包时,withCredentials属性就被激活了,我把它设置为 false。一切开始工作正常。

我最终的集线器构建器是这样的;

var connection = new signalR.HubConnectionBuilder()
            .withUrl('https://**chat.azurewebsites.net/chat', {
                accessTokenFactory: () => 'InR5cCI6IkpXVCJ9.eyJpZCI6I',
                withCredentials: false
            }).build();
Run Code Online (Sandbox Code Playgroud)

  • withCredentials: false 这对我有用。谢谢! (2认同)

lar*_*son 5

我也遇到过类似的问题,我纠结了6个小时。

原来我的起源末尾有一个斜线。

所以而不是:

.WithOrigins("https://aaa.azurewebsites.net/")
Run Code Online (Sandbox Code Playgroud)

使用:

.WithOrigins("https://aaa.azurewebsites.net")
Run Code Online (Sandbox Code Playgroud)

为什么最后的斜杠不被删除超出了我的理解。