Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 926
Dejan Avatar asked Aug 16 '19 07:08

Dejan


2 Answers

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.

like image 132
Henk Holterman Avatar answered Sep 17 '22 16:09

Henk Holterman


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);
like image 40
Ross P Avatar answered Sep 21 '22 16:09

Ross P