How to Get the Base Url of a Server-Side Blazor App
Asked Answered
M

3

21

I have a server-side blazor app and I need to know it's base url (e.g. https://localhost:1234 or https://my-host.com/appname).

In a traditional ASP.NET web application, I could inspect the Request property of a controller and retrieve the information from it (there's Scheme, Host, and PathBase for that). But since this is a server-side running Blazor app, there is no Request object (at least in my understanding and except maybe when serving the Index.cshtml).

How can I then know, to which URL my app has been deployed to and is running at?

Ideally, I would already have this information at startup time, so that I can configure my services accordingly.

Midwest answered 16/8, 2019 at 7:54 Comment(0)
S
32

Getting it inside a page is easy:

@inject NavigationManager Navigator

<p>@Navigator.BaseUri</p>

But you can't use a NavigationManager in the Startup class.

Shroudlaid answered 16/8, 2019 at 8:46 Comment(5)
That already helps a lot. I can build a work-around with this until somebody figures out how to get this at startup.Midwest
If there is a NuGet pkg required for this it would be nice if this information is always included with answers. It cannot be assumed that we would know.Silvers
I thumbed this up even in Oct 2020 because it lead me to the right direction but for those coming here now for .NET 5 have a look at the NavigationManager.Doorman
So, is it safe to say that there is no practical way to get the base URL in the Program.cs file where there is var builder = WebApplication.CreateBuilder(args); in a Blazor Server-side project? ---- Because, I saw a sample project of Blazor WebAssembly project, where the author used var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.HostEnvironment.BaseAddress in the Program.cs of the Client project.Oshea
@DamnVegetables - this is an old answer but mostly it is for Blazor-Server. No HostEnvironhment there.Shroudlaid
S
12

In .Net Core 3.0 onwards IUriHelper has been replaced by NavigationManager

To use inside a Blazor page:

    @inject NavigationManager NavigationManager

   //example usage
   var client = _clientFactory.CreateClient();
   client.BaseAddress = new Uri(NavigationManager.BaseUri);
Scapular answered 17/4, 2020 at 17:44 Comment(0)
P
0

@Navigator.BaseUri is not always working.

let's say your URL is something like the below :
https://localhost:7113/?ak=aoe4BFL/ then the @Navigator.BaseUri returns the whole string:

?NavigationManager.BaseUri
"https://localhost:7113/?ak=aoe4BFL/"
?NavigationManager.Uri
"https://localhost:7113/?ak=aoe4BFL/"
Porcine answered 3/7 at 14:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.