blazorblazor-server-side

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


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.


Solution

  • 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.