如何在Signalr Azure服务中启用Cors

时间:2018-11-30 13:52:25

标签: c# asp.net-core signalr signalr-hub asp.net-core-signalr

我试图在仅包含中心类的Web应用程序中使用Azure SignalR服务。当我尝试从另一个域访问集线器时,出现以下错误

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

在我的项目的startup.cs类中,我有:

`公共类启动     {         公共IConfiguration配置{ }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }


    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddCors(o => o.AddPolicy("Policy", builder =>
        {
            builder.AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials();
        }));
        services.AddSignalR().AddAzureSignalR(Configuration.GetConnectionString("AzureSignalRConnectionString")).AddJsonProtocol(options => options.PayloadSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings() { ContractResolver = new DefaultContractResolver()});
        services.AddSingleton(Configuration);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseCors("Policy");
        app.UseAzureSignalR(routes =>
        {
            routes.MapHub<GenericSocketHub>("/genericSocketHub");
        });
        app.UseMvc();

    }
}`

没有使用Azure SignalR服务,我没有任何CORS问题

1 个答案:

答案 0 :(得分:1)

尝试将.WithOrigins("[THE_DOMAIN_TO_UNBLOCK]");添加到您的策略中:

services.AddCors(o => o.AddPolicy("Policy", builder =>
    {
        builder.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials()
            .WithOrigins("[THE_DOMAIN_TO_UNBLOCK]");
    }));

还要确保在服务器上安装了最新版本的Microsoft.Asure.SignalR,在客户端上安装了最新版本的@aspnet/signalr

注意 signalr npm程序包与Azure SignalR不兼容。我是很难学到的。

以下内容适用于我的Angular7,.NET CORE 2.1和Azure SignalR设置。我的设置如下:

ConfigureServices

// Add CORS
  services.AddCors(options =>
  {
    options.AddPolicy("AllowAllOrigins",
              builder =>
              {
                builder
                  .AllowAnyOrigin()
                  .AllowAnyHeader()
                  .AllowCredentials()
                  .AllowAnyMethod()
                  .WithOrigins("http://localhost:4200");
              });
  });

  // Add Azure SignalR
  services.AddSignalR().AddAzureSignalR();

配置

app.UseCors("AllowAllOrigins");

app.UseAzureSignalR(routes =>
{
  routes.MapHub<NextMatchHub>("/nextmatch");
});

app.UseMvc(routes =>
{
  routes.MapRoute(
            name: "default",
            template: "api/{controller=Home}/{action=Index}/{id?}");
});

注意确保以与上面的示例相同的顺序添加各种实现。我无法解释为什么它对订单如此敏感,但这也是我的问题。