How to replace url-parameter?

后端 未结 8 761
谎友^
谎友^ 2021-01-12 01:27

given is an URL like http://localhost:1973/Services.aspx?idProject=10&idService=14.

What is the most straightforward way to replace both url-paramet

相关标签:
8条回答
  • 2021-01-12 01:48

    I have the same problem and i solved it with the following three lines of code that i get from the coments here (like Stephen Oberauer's solution, but less overenginieered):

        ' EXAMPLE: 
        '    INPUT:  /MyUrl.aspx?IdCat=5&Page=3
        '    OUTPUT: /MyUrl.aspx?IdCat=5&Page=4
        ' Get the URL and breaks each param into Key/value collection: 
        Dim Col As NameValueCollection = System.Web.HttpUtility.ParseQueryString(Request.RawUrl)
    
        ' Changes the param you want in the url, with the value you want
        Col.Item("Page") = "4"
    
        ' Generates the output string with the result (it also includes the name of the page, not only the params )
        Dim ChangedURL As String = HttpUtility.UrlDecode(Col.ToString())
    

    This is the solution using VB .NET but the conversion to C# is strightforward.

    0 讨论(0)
  • 2021-01-12 01:54

    I have recently released UriBuilderExtended, which is a library that makes editing of query strings on UriBuilder objects a breeze through extension methods.

    You basically just create a UriBuilder object with your current URL string in the constructor, modify the query through the extension methods, and build the new URL string from the UriBuilder object.

    Quick example:

    string myUrl = "http://www.example.com/?idProject=10&idService=14";
    
    UriBuilder builder = new UriBuilder(myUrl);
    
    builder.SetQuery("idProject", "12");
    builder.SetQuery("idService", "7");
    
    string newUrl = builder.Url.ToString();
    

    URL string is obtained from builder.Uri.ToString(), not builder.ToString() as it sometimes renders differently to what you'd expect.

    You can get the Library through NuGet.

    More examples here.

    Comments and wishes are most welcome.

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