Get url without querystring

前端 未结 18 1991
后悔当初
后悔当初 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:39
    Request.RawUrl.Split(new[] {'?'})[0];
    
    0 讨论(0)
  • 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&param2=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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-28 21:42
        string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
        string path = url.split('?')[0];
    
    0 讨论(0)
  • 2020-11-28 21:44

    simple example would be using substring like :

    string your_url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
    string path_you_want = your_url .Substring(0, your_url .IndexOf("?"));
    
    0 讨论(0)
  • 2020-11-28 21:45

    System.Uri.GetComponents, just specified components you want.

    Uri uri = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
    uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped);
    

    Output:

    http://www.example.com/mypage.aspx
    
    0 讨论(0)
  • 2020-11-28 21:50

    Here's a simpler solution:

    var uri = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
    string path = uri.GetLeftPart(UriPartial.Path);
    

    Borrowed from here: Truncating Query String & Returning Clean URL C# ASP.net

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