Getting started with SignalR using ASP.NET Core
This post is about getting started SignalR in ASP.NET Core. SignalR is a framework for ASP.NET developers that makes developing real-time web functionality easy. SignalR allows bi-directional communication between server and client. Servers can now push content to connected clients instantly as it becomes available.
First you need to create a ASP.NET Empty web application. You can do this using
dotnet new web -o HelloSignalR command. Next you need to add the reference of SignalR package. You can do this using dotnet add package command. Here is the command
dotnet add package Microsoft.AspNetCore.SignalR -v 1.0.0-alpha1-final. Once you’re add the reference, you need to open the project in your favourite editor, I am using VS Code here.
Add new file, name it as Chat.cs, you should inherit Hub class. Here is the implementation.
Unlike earlier versions of SignalR, there is no dynamic object, it is
InvokeAsync method. You need to pass the client method name and parameter(s).
Next you need to configure your application hub to handle the requests. For that you need to inject SignalR to request pipeline and configure chat hub endpoint to handle the requests. You can do this using UseSignalR extension method.
npm install @aspnet/signalr-client, once you run the command, npm command will show some warning, you can ignore it. Next copy
signalr-client-1.0.0-alpha1-final.min.js file from
node_modules\@aspnet\signalr-client\dist\browser folder to your scripts folder. You can reference this file in your HTML page. Here is pseudo code for simple chat with SignalR.
First you’re creating the connection object using
new signalR.HubConnection('/chat'), you need to give the SignalR endpoint as the parameter. Once you created the connection object, you can use
invoke method to invoke the method implemented in Hub. You can use
on method to listen for the events invoked from server.
If you want to use the Hub in Controller, you can add a parameter in the constructor of type
IHubContext<Chat>, ASP.NET Core runtime will inject this type to the controller, which you can be used to interact will client objects.
To use SignalR in Windows Forms / WPF / other native apps, you need to reference
Microsoft.AspNetCore.SignalR.Client package. Then you can use it like this.
I am passing the HubConnection to the Form poor mans DI :)
On methods to invoke and listen server side methods.
I am using SynchronizationContext to avoid the cross thread exceptions.
Source code available on GitHub
Happy Programming :)