AspNetCore.Docs/aspnetcore/signalr/dotnet-client.md

2.9 KiB

title author description manager monikerRange ms.author ms.custom ms.date ms.prod ms.technology ms.topic uid
ASP.NET Core SignalR .NET Client rachelappel Information about the ASP.NET Core SignalR .NET Client wpickett >= aspnetcore-2.1 rachelap mvc 05/18/2018 aspnet-core aspnet article signalr/dotnet-client

ASP.NET Core SignalR .NET Client

By Rachel Appel

The ASP.NET Core SignalR .NET client can be used by Xamarin, WPF, Windows Forms, Console, and .NET Core apps. Like the JavaScript client, the .NET client enables you to receive and send and receive messages to a hub in real time.

View or download sample code (how to download)

The code sample in this article is a WPF app that uses the ASP.NET Core SignalR .NET client.

Setup client

The Microsoft.AspNetCore.SignalR.Client package is needed for .NET clients to connect to SignalR hubs. To install the client library, run the following command in the Package Manager Console window:

Install-Package Microsoft.AspNetCore.SignalR.Client

Connect to a hub

To establish a connection, create a HubConnectionBuilder and call Build. The hub URL, protocol, transport type, log level, headers, and other options can be configured while building a connection. Configure any required options by inserting any of the HubConnectionBuilder methods into Build. Start the connection with StartAsync.

[!code-csharpBuild hub connection]

Call hub methods from client

InvokeAsync calls methods on the hub. Pass the hub method name and any arguments defined in the hub method to InvokeAsync. SignalR is asynchronous, so use async and await when making the calls.

[!code-csharpInvokeAsync method]

Call client methods from hub

Define methods the hub calls using connection.On after building, but before starting the connection.

[!code-csharpDefine client methods]

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

[!code-csharpCall client method]

Error handling and logging

Handle errors with a try-catch statement. Inspect the Exception object to determine the proper action to take after an error occurs.

[!code-csharpLogging]

Additional resources