Get raw URL from Microsoft.AspNet.Http.HttpRequest

后端 未结 8 713
醉酒成梦
醉酒成梦 2020-12-02 21:40

The HttpRequest class in Asp.Net 5 (vNext) contains (amongst other things) parsed details about the URL for the request, such as Scheme, Host

相关标签:
8条回答
  • 2020-12-02 22:33

    If you really want the actual, raw URL, you could use the following extension method:

    public static class HttpRequestExtensions
    {
        public static Uri GetRawUrl(this HttpRequest request)
        {
            var httpContext = request.HttpContext;
    
            var requestFeature = httpContext.Features.Get<IHttpRequestFeature>();
    
            return new Uri(requestFeature.RawTarget);
        }
    }
    

    This method utilizes the RawTarget of the request, which isn't surfaced on the HttpRequest object itself. This property was added in the 1.0.0 release of ASP.NET Core. Make sure you're running that or a newer version.

    NOTE! This property exposes the raw URL, so it hasn't been decoded, as noted by the documentation:

    This property is not used internally for routing or authorization decisions. It has not been UrlDecoded and care should be taken in its use.

    0 讨论(0)
  • 2020-12-02 22:37

    It looks like you can't access it directly, but you can build it using the framework:

    Microsoft.AspNetCore.Http.Extensions.UriHelper.GetFullUrl(Request)
    

    You can also use the above as an extension method.

    This returns a string rather than a Uri, but it should serve the purpose! (This also seems to serve the role of the UriBuilder, too.)

    Thanks to @mswietlicki for pointing out that it's just been refactored rather than missing! And also to @C-F to point out the namespace change in my answer!

    0 讨论(0)
提交回复
热议问题