Read and build request URLs in ASP.NET Core

ASP.NET Core exposes the request's scheme, host, path and query separately. Use its URL helpers instead of concatenating raw user input or treating a URL like a Windows path.

A display URL is for diagnostics and presentation. It is not automatically a trusted origin for security decisions or outbound redirects.

Build a query safely

Create dotnet new web -n UrlDemo -f net10.0 and replace Program.cs:

C#
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.WebUtilities;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/inspect", (HttpRequest request) => new {
	current = request.GetDisplayUrl(),
	next = QueryHelpers.AddQueryString("/search", "q", "A & B")
});
app.Run();

Run dotnet run --project UrlDemo --urls http://localhost:5088 from its parent directory and open /inspect on that address. The response includes the incoming URL and a relative search URL whose ampersand is encoded as data rather than another query separator.

Keep path and trust rules separate

Web paths use forward slashes. Path.Combine is for local filesystem paths and should not construct a web address. Use route generation for links to named application endpoints rather than hard-coding their route templates.

Behind a proxy, configure forwarded headers only from trusted proxies so the application sees the intended original scheme and host. Do not trust an arbitrary Host header to build password-reset links or external redirects. Use a configured public origin or validated host policy. Avoid logging sensitive query values while diagnosing URLs.

Official references

UriHelper.GetDisplayUrl(HttpRequest) Method (Microsoft.AspNetCore.Http.Extensions)
Returns the combined components of the request URL in a fully un-escaped form (except for the QueryString) suitable only for display. This format should not be used in HTTP headers or other HTTP operations.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.extensions.urihelper.getdisplayurl?view=aspnetcore-10.0
UriHelper.GetDisplayUrl
QueryHelpers.AddQueryString Method (Microsoft.AspNetCore.WebUtilities)
Append the given query keys and values to the URI.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webutilities.queryhelpers.addquerystring?view=aspnetcore-10.0
QueryHelpers.AddQueryString

Author: Herman Schoenfeld