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

后端 未结 3 1448
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 14:11

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

相关标签:
3条回答
  • 2020-12-14 14:53

    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)

    0 讨论(0)
  • 2020-12-14 15:06

    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

    0 讨论(0)
  • 2020-12-14 15:09

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题