Use SignalR service with my Blazor server app running on Azure App Service

David Thielen 3,121 Reputation points
2024-06-22T16:47:49.52+00:00

Hi all;

I've read in numerous places that adding a SignalR service to my Blazor app running on Azure App service, where the SignalR service connects to the remote client browser on one side and connects to my Blazor app on the other side should speed up my app. So I want to try this and measure the difference under load.

Unfortunately all my searching finds is how to write a SignalR web app. That is a very different thing. Can someone please point me to instructions on how to set up a SignalR service on top of my Blazor app on Azure App Service?

thanks - dave

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,597 questions
Azure SignalR Service
Azure SignalR Service
An Azure service that is used for adding real-time communications to web applications.
147 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,932 questions
Azure Startups
Azure Startups
Azure: A cloud computing platform and infrastructure for building, deploying and managing applications and services through a worldwide network of Microsoft-managed datacenters.Startups: Companies that are in their initial stages of business and typically developing a business model and seeking financing.
398 questions
{count} votes

Accepted answer
  1. Sina Salam 12,166 Reputation points
    2024-06-22T17:48:41.3666667+00:00

    Hello David Thielen,

    Welcome to the Microsoft Q&A and thank you for posting your questions here.

    Problem

    My understanding of your need is that you would like to try a scenario where the SignalR service connects to the remote client browser on one side and connects to your Blazor app on the other side to speed up your app and measure the difference under load.

    Solution

    To set up and test a SignalR service that connects a remote client browser to your Blazor app, and measure the performance difference under load, during my review and practices I have done similar these are the steps and resources used below, you can follow these steps to achieve the same:

    After you've created your Blazor WebAssembly (WASM) or Blazor Server project and add the SignalR client package to your Blazor project. Configure the SignalR client in your Blazor app, this is a similar code snippet:

    @using Microsoft.AspNetCore.SignalR.Client
    @code {
        private HubConnection hubConnection;
        protected override async Task OnInitializedAsync()
        {
            hubConnection = new HubConnectionBuilder()
                .WithUrl(NavigationManager.ToAbsoluteUri("/chathub"))
                .Build();
            hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
            {
                var encodedMsg = $"{user}: {message}";
                // Handle received message
            });
            await hubConnection.StartAsync();
        }
        private async Task SendMessage()
        {
            await hubConnection.SendAsync("SendMessage", "user", "Hello World!");
        }
        public bool IsConnected => hubConnection.State == HubConnectionState.Connected;
    }
    

    Secondly, add the SignalR service and configure the hub in your ASP.NET Core server and Configure the SignalR service in Startup.cs or Program.cs. This help to Setup SignalR Hub in the Server. To configure the hub in your ASP.NET Core server this is an example:

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

    To configure the SignalR service in Startup.cs or Program.cs this is an example:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSignalR();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
            endpoints.MapHub<ChatHub>("/chathub");
        });
    }
    

    Thirdly, on the remote client browser, establish a connection to the SignalR hub. This is an example of code:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.9/signalr.min.js"></script>
    <script>
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("/chathub")
            .build();
        connection.on("ReceiveMessage", (user, message) => {
            console.log(`${user}: ${message}`);
        });
        connection.start().catch(err => console.error(err.toString()));
        function sendMessage(user, message) {
            connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
        }
    </script>
    

    Lastly, I don't know what you would like to use for performance testing. If you are using tools like Apache JMeter, k6, or Locust to simulate load on your application. Then, measure response times and throughput with and without SignalR integration. Also, collect metrics such as CPU usage, memory consumption, and network latency. This is an example used in k6 for load testing:

    import http from 'k6/http';
    import { check, sleep } from 'k6';
    export let options = {
        stages: [
            { duration: '1m', target: 100 },
            { duration: '5m', target: 100 },
            { duration: '1m', target: 0 },
        ],
    };
    export default function () {
        let res = http.get('https://your-app-url.com');
        check(res, { 'status was 200': (r) => r.status == 200 });
        sleep(1);
    }
    

    I strongly believe by following these steps and read more from references provided, you can set up a SignalR service to connect remote clients with your Blazor app and perform load testing to measure performance differences.

    References

    Source: Azure SignalR Service Documentation. Accessed, 6/22/2024.

    Source: Tutorial: Use Azure SignalR Service with a Blazor Server app. Accessed, 6/22/2024.

    Source: Create an Azure SignalR Service instance. Accessed, 6/22/2024.

    Source: Azure Load Testing Documentation. Accessed, 6/22/2024.

    Source: Microsoft.Azure.SignalR on NuGet. Accessed, 6/22/2024.

    Source: Blazor Server Hosting Models. Accessed, 6/22/2024.

    Accept Answer

    I hope this is helpful! Do not hesitate to let me know if you have any other questions.

    ** Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful ** so that others in the community facing similar issues can easily find the solution.

    Best Regards,

    Sina Salam

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 67,016 Reputation points
    2024-06-24T17:00:34.2233333+00:00

    Perhaps you are referring to using the separate Azure Signal/R Service as the hub. There can be a performance boost for using the shared service rather than the Blazor app hosting the hub:

    https://github.com/aspnet/AzureSignalR-samples/tree/main/samples/ServerSideBlazor


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.