3
votes

I am working on asp.net core signalR. I want to make cross domain request.I have a javascript client,when i make hubConnection to cross domain signalR hub, then the below error shows, Access to XMLHttpRequest at 'https://localhost:44373/chatHub/negotiate?token=12' from origin 'https://localhost:44381' 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.

Javascript client code

var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44373/chatHub?token="+12).build();

Startup class in cross domain signalr project

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
    {
        builder
           .AllowAnyMethod()
           .AllowAnyHeader()
           .WithOrigins("*")
           .AllowCredentials();
    }));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddCors();
    services.AddSignalR();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    //app.UseCors(builder =>
    //{
    //    builder.WithOrigins("*")
    //       .AllowAnyHeader()
    //       .AllowAnyMethod()
    //       //.WithMethods("GET", "POST")
    //       .AllowCredentials();
    //});

    // ... other middleware ...
   // app.UseCors("CorsPolicy");
    app.UseSignalR(routes =>
    {
        routes.MapHub<ChatHub>("/chatHub");
    });

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

    app.UseMvc();
}
1
You have two services.AddCors calls, Is that necessary?Mat J
I am using just one services.AddCors()Ali
You have two calls, one above and below the services.AddMvc(). method.Mat J
O yes,no i did not these two callsAli

1 Answers

0
votes

In your startup class un-comment the following line // app.UseCors("CorsPolicy");

You've built the policy in your ConfigureServices() method, now you need to tell the app to use that policy in the Configure() method

EDIT:

In Response to your comment, if you want to allow any origin in your CORS policy, replace .WithOrigins("*") with .AllowAnyOrigin() instead.