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

后端 未结 3 1468
伪装坚强ぢ
伪装坚强ぢ 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 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;
        }
    }
    

提交回复
热议问题