How to build a query string for a URL in C#?

前端 未结 30 2555
借酒劲吻你
借酒劲吻你 2020-11-22 01:55

A common task when calling web resources from a code is building a query string to including all the necessary parameters. While by all means no rocket science, there are so

30条回答
  •  死守一世寂寞
    2020-11-22 02:23

    I wrote some extension methods that I have found very useful when working with QueryStrings. Often I want to start with the current QueryString and modify before using it. Something like,

    var res = Request.QueryString.Duplicate()
      .ChangeField("field1", "somevalue")
      .ChangeField("field2", "only if following is true", true)
      .ChangeField("id", id, id>0)
      .WriteLocalPathWithQuery(Request.Url)); //Uses context to write the path
    

    For more and the source: http://www.charlesrcook.com/archive/2008/07/23/c-extension-methods-for-asp.net-query-string-operations.aspx

    It's basic, but I like the style.

提交回复
热议问题