How to replace url-parameter?

后端 未结 8 830
谎友^
谎友^ 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:33

    Here is my implementation:

    using System;
    using System.Collections.Specialized;
    using System.Web; // For this you need to reference System.Web assembly from the GAC
    
    public static class UriExtensions
    {
        public static Uri SetQueryVal(this Uri uri, string name, object value)
        {
            NameValueCollection nvc = HttpUtility.ParseQueryString(uri.Query);
            nvc[name] = (value ?? "").ToString();
            return new UriBuilder(uri) {Query = nvc.ToString()}.Uri;
        }
    }
    

    and here are some examples:

    new Uri("http://host.com/path").SetQueryVal("par", "val")
    // http://host.com/path?par=val
    
    new Uri("http://host.com/path?other=val").SetQueryVal("par", "val")
    // http://host.com/path?other=val&par=val
    
    new Uri("http://host.com/path?PAR=old").SetQueryVal("par", "new")
    // http://host.com/path?PAR=new
    
    new Uri("http://host.com/path").SetQueryVal("par", "/")
    // http://host.com/path?par=%2f
    
    new Uri("http://host.com/path")
        .SetQueryVal("p1", "v1")
        .SetQueryVal("p2", "v2")
    // http://host.com/path?p1=v1&p2=v2
    

提交回复
热议问题