Search code examples
c#angularasp.net-coresignalr

CORS error when using SignalR Core in angular app


In CORS configuration, I am allowing OPTIONS method, but when I send a request, an error is thrown

OPTIONS http://x.x.x.x:port/function 405 (Method Not Allowed)

my CORS Policy in ConfigureServices method in Startup.cs is as follows:

services.AddCors(options =>
{
    options.AddPolicy("AllowAny", x =>
  {
    x.AllowAnyOrigin()
     .AllowAnyHeader()
     .WithMethods("POST", "OPTIONS");
  });
});

And it is used as follows:

app.UseCors("AllowAny");

Hub Code:

public async Task SendMessage(string user, string message) {
   string outputMessage = SensorsControl.controlSensors(message.ToString()); 
   await Clients.All.SendAsync("ReceiveMessage", user, outputMessage);
}

SignalR Code in angular:

this._hubConnection = new HubConnection('http://x.x.x.x:port/function'); 
this._hubConnection.start() 
                   .then(() => console.log('Connection started!')) 
                   .catch(err => console.log('Error while establishing connection')); 
this._hubConnection.on('ReceiveMessage', (user: string, outputMessage: string) => 
{ 
  const text = ${user}: ${outputMessage}; this.messages.push(text); 
}); 

Solution

  • I solved it guys :D The problem was that my angular app was hosted on localhost which was supposed to be my IPv4 IP, but it turned to be 127.0.0.1 which is not understood by the SignalR server. With no changes, I served angular using ng serve --host 0.0.0.0, and then connected using my IPv4 IP, worked as charm :D thanks for your help tho! Cheers!!