Swimburger

How to get the full public URL of ASP.NET Core

Niels Swimberghe

Niels Swimberghe - - .NET

Follow me on Twitter, buy me a coffee

URLs are what makes the web the web. In ASP.NET Core Controllers, Razor Pages, and Razor views, there's a Request property which gives you access to the HttpRequest instance. The HttpRequest object gives you access to scheme, host (which is the domain and port), path, query string, body content, and headers of the incoming HTTP request.

If you need to know what the full URL is of your web application, you can put the URL together by grabbing the Scheme, Host, PathBase, Path, and QueryString and combining it like this:

$"{Request.Scheme}://{Request.Host}{Request.PathBase}{Request.Path}{Request.QueryString}"

Maybe you're only interested in the URL without the path and query string, in which case you can omit the PathBase, Path, and QueryString parameter from the string interpolation:

$"{Request.Scheme}://{Request.Host}"

If you want to generate URLs for your application, I suggest you use the UrlHelper as explained in this blog post about generating absolute URLs.

If you're using Minimal APIs, there's no Request property accessible to you, but you can accept an instance of HttpRequest as a parameter to your endpoint callback like this:

app.MapGet("/hello-world", (HttpRequest request) =>
    {
        return $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}{request.QueryString}";
    }
);

What if there's no HTTP request?

If there is no HTTP request that you're handling in your code, like when you're doing some background processing using a BackgroundWorker, you'll need to get the scheme and host some other way. You could store your desired scheme and host into your configuration, or combine them together in a single property and store it into your configuration. Once configured, extract it from configuration and use it to build your absolute URL.

Be mindful of the fact that web application can be requested from multiple URLs depending on the network and infrastructure configuration. So even though you could simply store the full public URL in configuration, that may not be the only URL that users use.

Related Posts

Related Posts