4
votes

I am trying to use the Azure SignalR Service in a web app that only contains a hub class. When I try to access from another domain to the hub I get the following error

"Access to XMLHttpRequest at 'https://*/genericSocketHub/negotiate' from origin 'https://localhost:44303' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.".

In the startup.cs class of my project I have:

` public class Startup { public IConfiguration Configuration { get; }

    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();

    }
}`

Without using Azure SignalR Service I didn't have any CORS issues

1

1 Answers

3
votes

Try adding .WithOrigins("[THE_DOMAIN_TO_UNBLOCK]"); to your policy:

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

Also make sure that you have the latest version of Microsoft.Asure.SignalR installed on the server along with the latest @aspnet/signalr installed on the client.

NOTE The signalr npm package is not compatible with Azure SignalR. I learned this the hard way..

The following worked for my setup which is Angular7, .NET CORE 2.1 and Azure SignalR. My setup looks like this:

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();

Configure

app.UseCors("AllowAllOrigins");

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

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

NOTE Make sure that the various implementations are added in the same order as my example shows above. I cannot explain why it is sensitive about the order but this was also an issue on my end.