I found a blog post that shows how to \"shim\" familiar things like HttpResponseMessage back into ASP.NET Core MVC, but I want to know what\'s the new native way to do the s
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)
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 headersThese are extension method from the following namespace : Microsoft.AspNetCore.Http.Extensions
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;
}
}