简体   繁体   中英

.NetCore SignalR CORS is not allowing client calls

In my .Netcore application I am using SingalR to pass messages to different clients

My code is like this

      services.AddCors( options =>
                          {
                              options.AddPolicy( "mypolicy", builder =>
                                                 {
                                                     builder.AllowAnyHeader();
                                                     builder.AllowAnyMethod();
                                                     builder.AllowAnyOrigin();
                                                     builder.AllowCredentials();
                                                 } );
                          } );

        services.AddMvc();
        services.Configure<MvcOptions>( options => { options.Filters.Add( new CorsAuthorizationFilterFactory( "mypolicy" ) ); } );
        services.Configure<SignalROptions>( options => options.Hubs.EnableDetailedErrors = true );

My .Netcore application is running here http://localhost:88 and I am accessing it through http://localhost

If I try to use

        builder.WithOrigins("http://localhost");

I am able to access the SignalR services. My problem is I will be accessing the .NetCore application from different clients that means from different client domains so it is not practically possible to add all those clients in WithOrgins.

So builder.AllowAnyOrigin(); is the best solution for me.

Can anyone tell me how to achieve it.

You should call app.UseCors() method which applies CORS policies to all the apps endpoints via CORS Middleware.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
       app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseCors(); 

    app.UseHttpsRedirection();
    app.UseMvc();
}

more about cors you can find here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM