Access to XMLHttpRequest has been blocked origin ASP.NET CORE 2.2.0 / Angular 8 / signalr1.0.0 [(CORS Policy-Access-Control-Allow-Origin) failed]

前端 未结 2 925
迷失自我
迷失自我 2021-01-20 05:58

nugetPackage on .net core2.2.0:

signalr 1.0.0 + ASP.Core2.2.0

I\'m using angular to connect use signalr:

package.json: \"@aspnet/signalr\": \"1.1.0\

相关标签:
2条回答
  • 2021-01-20 06:54

    You should apply your policy in Configure method:

    public void Configure 
    {
        app.UseResponseCompression();
    
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // 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("MyPolicy");
    }
    

    UPDATE:

    If you are using localhost as http://localhost:4200, then try to set it in your configuration:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options => options.AddPolicy("ApiCorsPolicy", build =>
        {                
            build.WithOrigins("http://localhost:4200")
                 .AllowAnyMethod()
                 .AllowAnyHeader();
            }));
            // ... other code is omitted for the brevity
         }
    }
    

    And Configure method:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCors("ApiCorsPolicy");
        app.UseHttpsRedirection();        
        app.UseMvc();
    }
    
    0 讨论(0)
  • 2021-01-20 06:58

    You should add your CORS like this:

    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://localhost:4200")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials()
            .SetIsOriginAllowed((host) => true));
    });
    

    Note:

    The order is important!

    0 讨论(0)
提交回复
热议问题