How to remove the port number from a url string

前端 未结 8 612
清酒与你
清酒与你 2021-02-02 04:57

I have the following code snippet:

string tmp = String.Format(\"

        
相关标签:
8条回答
  • 2021-02-02 05:24
    var url = "http://google.com:80/asd?qwe=zxc#asd";
    var regex = new Regex(@":\d+");
    var cleanUrl = regex.Replace(url, "");
    

    the solution with System.Uri is also possible but will be more bloated.

    0 讨论(0)
  • 2021-02-02 05:27

    Ok, thanks I figured it out...used the KISS principle...

    string redirectstr = String.Format(
       "http://localhost/Gradebook/AcademicHonestyGrid.aspx?StudentID={0}&ClassSectionId={1}&uid={2}", 
       studid, 
       intSectionID, 
       HttpUtility.UrlEncode(encrypter.Encrypt(uinfo.ToXml())));
    
    Response.Redirect(redirectstr );
    

    works fine for what I am doing which is a test harness

    0 讨论(0)
  • 2021-02-02 05:35

    A more generic solution (works with http, https, ftp...) based on Ian Flynn idea. This method does not remove custom port, if any. Custom port is defined automatically depending on the protocol.

    var uriBuilder = new UriBuilder("http://www.google.fr/");
    if (uriBuilder.Uri.IsDefaultPort)
    {
        uriBuilder.Port = -1;
    }
    return uriBuilder.Uri.AbsoluteUri;
    
    0 讨论(0)
  • 2021-02-02 05:36

    I would use the System.Uri for this. I have not tried, but it seems it's ToString will actually output what you want:

    var url = new Uri("http://google.com:80/asd?qwe=asdff");
    var cleanUrl = url.ToString();
    

    If not, you can combine the components of the url-members to create your cleanUrl string.

    0 讨论(0)
  • 2021-02-02 05:42

    You can use the UriBuilder and set the value of the port to -1

    and the code will be like this:

    Uri tmpUri = new Uri("http://LocalHost:443/Account/Index");
    UriBuilder builder = new UriBuilder(tmpUri);
    builder.Port = -1;
    Uri newUri = builder.Uri;
    
    0 讨论(0)
  • 2021-02-02 05:47

    Use the Uri.GetComponents method. To remove the port component you'll have to combine all the other components, something like:

    var uri = new Uri( "http://www.example.com:80/dir/?query=test" );
    var clean = uri.GetComponents( UriComponents.Scheme | 
                                   UriComponents.Host | 
                                   UriComponents.PathAndQuery, 
                                   UriFormat.UriEscaped );
    

    EDIT: I've found a better way:

    var clean = uri.GetComponents( UriComponents.AbsoluteUri & ~UriComponents.Port,
                                   UriFormat.UriEscaped );
    

    UriComponents.AbsoluteUri preservers all the components, so & ~UriComponents.Port will only exclude the port.

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