ASP.NET Core SignalR JavaScript client

By Rachel Appel

The ASP.NET Core SignalR JavaScript client library enables developers to call server-side hub code.

View or download sample code (how to download)

Install the SignalR client package

The SignalR JavaScript client library is delivered as an npm package. If you're using Visual Studio, run npm install from the Package Manager Console while in the root folder. For Visual Studio Code, run the command from the Integrated Terminal.

npm init -y
npm install @aspnet/signalr

npm installs the package contents in the node_modules\@aspnet\signalr\dist\browser folder. Create a new folder named signalr under the wwwroot\lib folder. Copy the signalr.js file to the wwwroot\lib\signalr folder.

Use the SignalR JavaScript client

Reference the SignalR JavaScript client in the <script> element.

<script src="~/lib/signalr/signalr.js"></script>

Connect to a hub

The following code creates and starts a connection. The hub's name is case insensitive.

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub")
    .configureLogging(signalR.LogLevel.Information)
    .build();
connection.start().catch(err => console.error(err.toString()));

Cross-origin connections

Typically, browsers load connections from the same domain as the requested page. However, there are occasions when a connection to another domain is required.

To prevent a malicious site from reading sensitive data from another site, cross-origin connections are disabled by default. To allow a cross-origin request, enable it in the Startup class.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SignalRChat.Hubs;

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

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc();

            services.AddCors(options => options.AddPolicy("CorsPolicy", 
            builder => 
            {
                builder.AllowAnyMethod().AllowAnyHeader()
                       .WithOrigins("http://localhost:55830")
                       .AllowCredentials();
            }));

            services.AddSignalR();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseCors("CorsPolicy");
            app.UseSignalR(routes => 
            {
                routes.MapHub<ChatHub>("/chathub");
            });
            app.UseMvc();            
        }
    }
}

Call hub methods from client

JavaScript clients call public methods on hubs via the invoke method of the HubConnection. The invoke method accepts two arguments:

  • The name of the hub method. In the following example, the method name on the hub is SendMessage.

  • Any arguments defined in the hub method. In the following example, the argument name is message.

    connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
    

Call client methods from hub

To receive messages from the hub, define a method using the on method of the HubConnection.

  • The name of the JavaScript client method. In the following example, the method name is ReceiveMessage.
  • Arguments the hub passes to the method. In the following example, the argument value is message.
connection.on("ReceiveMessage", (user, message) => { 
    const encodedMsg = user + " says " + message;
    const li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

The preceding code in connection.on runs when server-side code calls it using the SendAsync method.

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

SignalR determines which client method to call by matching the method name and arguments defined in SendAsync and connection.on.

Note

As a best practice, call the start method on the HubConnection after on. Doing so ensures your handlers are registered before any messages are received.

Error handling and logging

Chain a catch method to the end of the start method to handle client-side errors. Use console.error to output errors to the browser's console.

connection.start().catch(err => console.error(err.toString()));

Setup client-side log tracing by passing a logger and type of event to log when the connection is made. Messages are logged with the specified log level and higher. Available log levels are as follows:

  • signalR.LogLevel.Error – Error messages. Logs Error messages only.
  • signalR.LogLevel.Warning – Warning messages about potential errors. Logs Warning, and Error messages.
  • signalR.LogLevel.Information – Status messages without errors. Logs Information, Warning, and Error messages.
  • signalR.LogLevel.Trace – Trace messages. Logs everything, including data transported between hub and client.

Use the configureLogging method on HubConnectionBuilder to configure the log level. Messages are logged to the browser console.

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub")
    .configureLogging(signalR.LogLevel.Information)
    .build();