URL Querystring - Find, replace, add, update value

2019-06-15 07:54发布

We inherited some C# code as part of a project from another company which does URL redirects that modifies the existing query string, changing values of items, adding new params, etc as needed. The issue however is that the code is buggy at best, and ends up duplicating items in the query string instead of updating them properly. The code works on the first pass but on additional calls the duplication issues become apparent.

Ex: MyPage.aspx?startdate=08/22/09&startdate=09/22/09

Instead of duplicating the item it needs to be either updated with the new value if it already exists, or added if not there already.

Is there a C# class or set of functions for handling query strings, allowing a simple means to access and update/add parameters that gets around these issues instead of the blind add approach that seems to be in use now with the code? This needs to be able to handle multiple parameters that may or may not exists at all times and be added and updated on subsequent calls.

We would sooner use existing logic than recreate something if possible so as to get this resolved quickly in a semi standard way for future maintainability and reuse.

4条回答
仙女界的扛把子
2楼-- · 2019-06-15 08:15

The WCF REST Starter Kit available on ASP.NET also include a new "HttpQueryString" helper class that will most likely be included in the .NET 4.0 time frame into the base class library.

See an excellent screencast on how to use this utility class here:

http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-HttpClient-Query-String-and-Form-Input-Management/

Marc

查看更多
Summer. ? 凉城
3楼-- · 2019-06-15 08:27

You can access and manipulate all values of your Querystring through the Request.QueryString collection. Here's a link.

查看更多
放荡不羁爱自由
4楼-- · 2019-06-15 08:28

this seems a basic design problem.

instead of updating the current query string, what SHOULD be done is simply adding all the parameters to the base at every time.

sure, you CAN update it, but (pseudocode)

if querystring exists
  then update query string
else
  add query string

will get crazy when you start using more than 1 variable.

redesign would be best, effort allowing.

查看更多
The star\"
5楼-- · 2019-06-15 08:33

Yes I would suggest converting the querystring to a collection by using HttpUtility.ParseQueryString()

You can then find/add/update/replace values directly in the collection, before re-creating the querystring from this collection.

This should make it easier to spot duplicates.

查看更多
登录 后发表回答