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/