Get url without querystring

前端 未结 18 2161
后悔当初
后悔当初 2020-11-28 21:24

I have a URL like this:

http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye

I want to get http://www.example.com/mypage

18条回答
  •  囚心锁ツ
    2020-11-28 21:42

    Here's an extension method using @Kolman's answer. It's marginally easier to remember to use Path() than GetLeftPart. You might want to rename Path to GetPath, at least until they add extension properties to C#.

    Usage:

    Uri uri = new Uri("http://www.somewhere.com?param1=foo¶m2=bar");
    string path = uri.Path();
    

    The class:

    using System;
    
    namespace YourProject.Extensions
    {
        public static class UriExtensions
        {
            public static string Path(this Uri uri)
            {
                if (uri == null)
                {
                    throw new ArgumentNullException("uri");
                }
                return uri.GetLeftPart(UriPartial.Path);
            }
        }
    }
    

提交回复
热议问题