How to configure nginx with SignalR ASP NET Core?

Viewed 60

I had an issue with this recently and had to spend a lot of time configuring it.

So let me tell you the problem.

I am trying to use SignalR but it works on local but not on server when using Nginx.

So here are my code:

Cors Policy:

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

            });

SignalR:

//this is in ConfigureServices
services.AddSignalR();
//this is in Configure
app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<NotificationHub>("/notification");
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
                
            });

Frontend Side:

start() {
    let token = 'myjwttoken';
    let url = 'https://localhost:5001/notification';
    const connection = new HubConnectionBuilder()
      .withUrl(url, {
        accessTokenFactory: () => {
          return token;
        },
      })
      .configureLogging(LogLevel.Information)
      .build();
    connection
      .start()
      .then(() => {
        console.log('Connected');
      })
      .catch(err => {
        console.log('Disconnected');
        console.log(err);
      });
  }

Now this works in Local without any issue.

1 Answers

So in order for this to work on a Server Prod/Dev environment EC2 or VM or any Linux Server.

server {
    server_name   api.com;
    location / {
        proxy_pass         http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }

    location /notification {
        proxy_pass         http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection "Upgrade";
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}
Related