Posted by Anuraj on Wednesday, October 3, 2018 Reading time :2 minutes
For this post, I am creating a ASP.NET Core web api application, which will expose SignalR hub, and a standalone blazor client app, which can interact with Web API and consume the SignalR endpoint. You can create a web api app using
dotnet new webapi command.
Here is the Web API startup class code -
And here is the startup class code -
In the above code, I am exposing a SignalR endpoint on
/chathub URL. And I am running the client on
http://localhost:5050, because of that, I am enabling
CORS for the particular URL. In production scenarios, you need to use the exact client URL. And finally,
Now you can create a standalone blazor app using command
dotnet new blazor command. Next you need to add
Blazor.Extensions.SignalR package reference to the client. You can do this by
dotnet add package Blazor.Extensions.SignalR --version 0.1.6 command. Next in your index.cshtml file, you can write code to connect to Hub, and event handlers.
OnInitAsync method, I am connecting to the Web API running on port 5001, and creating an event handler for
broadcastMessage method, which is the method used in
ChatHub class. On the event handler method, I am concating the name and message parameters, and appending to a list. The
StateHasChanged method will update the bindings and in the HTML, I am looping through the messages collection and displaying it in
SendMessage method will invoke
Send method in the hub with name and message parameters. And here is the HTML Code.
You can run the Web API app with
dotnet run command, and to run the client app, you need to provide the port number. You can do like this.
dotnet run --server.urls "http://*:5050" from the Blazor project directory.
This way you can integrate SignalR with Blazor client. You can find out more details about the BlazorExtensions project here.
Happy Programming :)