Best way to add key / value to existing URL string?

I want to create a link on my page where a key / value pair is dynamically added so that:

Default.aspx?key1=value1

becomes:

Default.aspx?key1=value1&key2=value2

For an existing request to store any keys in the URL. In addition, if there are no keys, then my key will be added along with " ? ", As it will be needed.

I could easily write some logic that does this, but it looks like what should matter to the platform. Is there a way to add keys to the query string without writing my own logic?

+4
source share
4 answers

I know, it is strange that this is not supported properly in the .NET Framework. Several extensions for UriBuilder will do what you need.

+5
source

You can use the UriBuilder class. See the Example in Request Properties . FWIW, ASP.NET MVC includes the UrlHelper class, which does just that for the MVC environment. Perhaps you should consider adding an extension method to the HttpRequest class, which takes a dictionary and returns a suitable Url based on a given query and dictionary values. Thus, you will need to write it only once.

+3
source

I always created them myself.

 string url = Request.UrlReferrer.PathAndQuery; (url[url.Length - 1] != '?' ? "?" : "&") + Url.Encode(key) + "=" + Url.Encode(key) 
  • Url.Encode is something in ASP.NET MVC
0
source

If you are using the ASP.NET MVC Framework release, I believe there is a TabBuilder object that will allow you to do this. Otherwise, you can use UriBuilder, but you still have to do some parsing. There are some utility classes on the Internet as well, but I never used them, so I don’t know how well they work:

0
source

All Articles