How to  make sure Blazor properly handles requests from Nginx

How to make sure Blazor properly handles requests from Nginx

In the scenario I have added the option to my Blazor server app to support base paths and custom ports so you’ll see this in the proposed solution. Open Program.cs, where I added the following:

It’s important to note that I’m hosting a local API in my Blazor server app, since this is all running on the server we need to specify localhost and the port used.

if (!builder.Environment.IsDevelopment())
{
    builder.WebHost.UseUrls($"http://*:{port}");
}
if (builder.Environment.IsDevelopment())
{
    builder.Services.AddHttpClient("NoSSL", client =>
    {
        client.BaseAddress = new Uri($"https://localhost:7157");
    }).AddHttpMessageHandler<AuthTokenHandler>();
}
else
{
    builder.Services.AddHttpClient("NoSSL", client =>
{
    if (string.IsNullOrEmpty(basePath))
    {
        client.BaseAddress = new Uri($"http://localhost:{port}");
    }
    else
    {
        client.BaseAddress = new Uri($"http://localhost:{port}{basePath}");
    }
});

I also included SignalR in my app (no, not the built in Blazor SignalR but an own implemenation). This is client side stuff so here we need to set it up as following:

var connection = new HubConnectionBuilder()
    .WithUrl($"{NavigationManager.BaseUri}hub")
    .WithAutomaticReconnect()
    .Build();

connection.On("updateSomething", async (SomeClass someClass) =>
{
    await InvokeAsync(async () =>
    {
        // Do the stuff you need here
        StateHasChanged();
    });
});

await connection.StartAsync();

NavigationManager.BaseUri will be the external url so https://something. When looking at the console, we see the Signalr is connecting using the external URL:

Information: Normalizing '_blazor' to 'https://www.yellow-cab.nl/_blazor'.

Leave a Reply

Your email address will not be published. Required fields are marked *