Replace item in querystring

前端 未结 11 1479
甜味超标
甜味超标 2020-12-11 01:23

I have a URL that also might have a query string part, the query string might be empty or have multiple items.

I want to replace one of the items in the query string

相关标签:
11条回答
  • 2020-12-11 01:26

    I use following method:

        public static string replaceQueryString(System.Web.HttpRequest request, string key, string value)
        {
            System.Collections.Specialized.NameValueCollection t = HttpUtility.ParseQueryString(request.Url.Query);
            t.Set(key, value);
            return t.ToString();
        }
    
    0 讨论(0)
  • 2020-12-11 01:26

    I agree with Cerebrus. Sticking to the KISS principle, you have the querystring,

    string querystring = myURI.Query; 
    

    you know what you are looking for and what you want to replace it with.

    So use something like this:-

    if (querystring == "") 
      myURI.Query += "?" + replacestring; 
    else 
      querystring.replace (searchstring, replacestring); // not too sure of syntax !!
    
    0 讨论(0)
  • 2020-12-11 01:31

    I found this was a more elegant solution

    var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());
    qs.Set("item", newItemValue);
    Console.WriteLine(qs.ToString());
    
    0 讨论(0)
  • 2020-12-11 01:31

    You can speed up RegExps by precompiling them.

    Check out this tutorial

    0 讨论(0)
  • 2020-12-11 01:34
    string link = page.Request.Url.ToString();
    
    if(page.Request.Url.Query == "")
        link  += "?pageIndex=" + pageIndex;
    else if (page.Request.QueryString["pageIndex"] != "")
    {
        var idx = page.Request.QueryString["pageIndex"];
        link = link.Replace("pageIndex=" + idx, "pageIndex=" + pageIndex);
    }
    else 
        link += "&pageIndex=" + pageIndex;
    

    This seems to work really well.

    0 讨论(0)
  • 2020-12-11 01:37

    Lets have this url: https://localhost/video?param1=value1

    At first update specific query string param to new value:

    var uri = new Uri("https://localhost/video?param1=value1");
    var qs = HttpUtility.ParseQueryString(uri.Query);
    qs.Set("param1", "newValue2");
    

    Next create UriBuilder and update Query property to produce new uri with changed param value.

    var uriBuilder = new UriBuilder(uri);
    uriBuilder.Query = qs.ToString();
    var newUri = uriBuilder.Uri;
    

    Now you have in newUri this value: https://localhost/video?param1=newValue2

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