0

I am using SignalR in .net core 3.1 with angular 9. it's providing error. Access to XMLHttpRequest at 'http://localhost:5000/chathub/negotiate' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

I am going to share my startup where I have configured SignalR and also providing a hub that is created on .net core. I am also providing a client-side connection code that is written in angular 9.

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

    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllers();
        services.AddSignalR();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
         app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
             .AllowAnyHeader());

        app.UseRouting();
        app.UseAuthorization();
          app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<ChatHub>("/chathub");
        });
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();
    }
}

This is my Hub.

public class ChatHub: Hub
{
    public static List<UserModel> userModel = new List<UserModel>();

    
    public async Task SendMessage(UserModel model)
    {
        await Clients.All.SendAsync("ReceiveMessage", model);
    }
}

And this is my client-side code that is written in angular

export class StartComponent implements OnInit {

public _apiservice : ApiServiceService;
private _hubConnection: HubConnection; 
constructor(apiservice : ApiServiceService) {
  this._apiservice = apiservice;
  this.createConnection();  
  this.startConnection();  

}

 register(){
   this._apiservice.registerUser();
 }

  ngOnInit(): void {
  }

  private startConnection(): void {  

    this._hubConnection  
    .start()  
    .then(() => {  
    console.log('Hub connection started');   
   })  
  .catch(err => {  
    console.log('Error while establishing connection, retrying...');  
    // setTimeout(function () { this.startConnection(); }, 5000);  
    });  
  } 
  private createConnection() {  
         this._hubConnection = new HubConnectionBuilder()  
         .withUrl("http://localhost:5000/" + 'chathub')  
         .build();  
            console.log('hub connection')
   }  

 }

I am working on a local computer. my angular app is running on the http://localhost:4200/ and dot net core application is running on http://localhost:5000/

mxmissile
  • 11,464
  • 3
  • 53
  • 79
Manoj
  • 57
  • 3
  • Does this answer your question? [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\]](https://stackoverflow.com/questions/59468525/access-to-xmlhttprequest-has-been-blocked-origin-asp-net-core-2-2-0-angular-8) – Kiril1512 Aug 24 '20 at 16:41
  • Thanks for response but this link does not solve this problem. kindly suggest. – Manoj Aug 24 '20 at 17:13
  • in Dotnet core 3.1 Signlar replaced by app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub("/chathub"); }); So kindly suggest what is the problem. – Manoj Aug 24 '20 at 17:14
  • When I call API it's working fine but Signalr is not working. – Manoj Aug 24 '20 at 17:39
  • But you configured CORS like my answer on that question? – Kiril1512 Aug 24 '20 at 17:45
  • Yes, I configured the same but the same problem. i used services.AddCors(o => o.AddPolicy("MyPolicy", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); in my service. – Manoj Aug 24 '20 at 17:50
  • I also tried configuration like services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://localhost:4200") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() .SetIsOriginAllowed((host) => true)); }); but still not working. – Manoj Aug 24 '20 at 17:52
  • 2
    app.UseCors need to be put between `app.UseRouting();` and `app.UseAuthorization();`You can see `Calls the UseCors extension method and specifies the _myAllowSpecificOrigins CORS policy. UseCors adds the CORS middleware. The call to UseCors must be placed after UseRouting, but before UseAuthorization.` in the [link](https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#cors-with-named-policy-and-middleware). – Yiyi You Aug 27 '20 at 08:21

0 Answers0