What is the ASP.NET Core MVC equivalent to Request.RequestURI?

Personally, I use :

new Uri(request.GetDisplayUrl())
  • GetDisplayUrl fully un-escaped form (except for the QueryString)
  • GetEncodedUrl - fully escaped form suitable for use in HTTP headers

These are extension method from the following namespace : Microsoft.AspNetCore.Http.Extensions


A cleaner way would be to use a UriBuilder:

private static Uri GetUri(HttpRequest request)
{
    var builder = new UriBuilder();
    builder.Scheme = request.Scheme;
    builder.Host = request.Host.Value;
    builder.Path = request.Path;
    builder.Query = request.QueryString.ToUriComponent();
    return builder.Uri;
}

(not tested, the code might require a few adjustments)


Here's a working code. This is based off @Thomas Levesque answer which didn't work well when the request is from a custom port.

public static class HttpRequestExtensions
{
    public static Uri ToUri(this HttpRequest request)
    {
        var hostComponents = request.Host.ToUriComponent().Split(':');

        var builder = new UriBuilder
        {
            Scheme = request.Scheme,
            Host = hostComponents[0],
            Path = request.Path,
            Query = request.QueryString.ToUriComponent()
        };

        if (hostComponents.Length == 2)
        {
            builder.Port = Convert.ToInt32(hostComponents[1]);
        }

        return builder.Uri;
    }
}