Author : HASSAN MD TAREQ

SignalR in ASP.Net Core

  • ASP.Net Core 3.0+ => SignalR is a middleware
  • add SignalR dependency in ConfigureServices(...)
  • use SignalR in Configure()
  • Both MVC and Razor pages can be used for SignalR app

ConfigureServices

Startup.cs

public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {
        //... ... ...
		
		services.AddRazorPages();
		services.AddSignalR();
    }

    public void Configure(IApplicationBuilder app)
    {
        //... ... ...
    }
}

Configure

Startup.cs

public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {
        //... ... ...
    }

    public void Configure(IApplicationBuilder app)
    {
		// ... ... ...
	
		app.UseRouting();

		app.UseAuthorization();

		app.UseEndpoints(endpoints =>
		{
			endpoints.MapRazorPages();
			endpoints.MapHub<ChatHub>("/chatHub");
		});
    }
}

Allow CORS

  • If hub is running in different server, browser will block client-server communication (no CORS by default)
  • we need to allow CORS so that client can communicate with server (when hub runnig in different server)

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
	// ... ... ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{

	// ... ... ...
	
	app.UseCors(builder => {
		builder.WithOrigins("https://www.hovermind.com")
		.AllowAnyHeader()
		.WithMethods("GET", "POST")
		.AllowCredentials();
	});
	
	// ... ... ...
}