简体   繁体   English

将键/值添加到现有URL字符串的最佳方法?

[英]Best way to add a key/value to an existing URL string?

I want to generate a link on my page where a key/value pair is added to the URL dynamically so that: 我想在我的页面上生成一个链接,其中一个键/值对动态添加到URL,以便:

Default.aspx?key1=value1

Becomes: 变为:

Default.aspx?key1=value1&key2=value2

So that the existing query retains any keys in the URL. 这样现有的查询就会保留URL中的任何键。 Also, if there are no keys, then my key would be added, along with the ' ? 此外,如果没有密钥,那么我的密钥将被添加,以及' ? ' since it would be needed. '因为它是需要的。

I could easily write some logic that does this, but this seems like something that the framework should have a utiltity for. 我可以轻松地编写一些执行此操作的逻辑,但这似乎是框架应具有的实用性。 Is there any way to add keys to a query string without writing my own logic for it? 有没有办法在不编写自己的逻辑的情况下为查询字符串添加键?

I know, it's strange this is not supported properly in the .NET Framework. 我知道,在.NET Framework中不能正确支持这一点很奇怪。 A couple of extensions to UriBuilder will do what you need though. UriBuilder的一些扩展将尽你所能

You can use the UriBuilder class. 您可以使用UriBuilder类。 See the example in the Query property documentation. 请参阅Query属性文档中的示例。 FWIW, ASP.NET MVC includes the UrlHelper class that does exactly this sort of thing for the MVC framework. FWIW,ASP.NET MVC包含UrlHelper类,它为MVC框架完成了这类工作。 You might want to think about adding an extension method to the HttpRequest class that takes a dictionary and returns a suitable Url based on the given request and the dictionary values. 您可能想要考虑向HttpRequest类添加扩展方法,该方法接受字典并根据给定的请求和字典值返回合适的Url。 This way you'd only have to write it once. 这样你只需要写一次。

I've always been generating 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 Url.Encode是ASP.NET MVC中的一个东西

If you're using the ASP.NET MVC Framework release, I believe there is a TabBuilder object that will allow you to do that. 如果您正在使用ASP.NET MVC Framework版本,我相信有一个TabBuilder对象可以让您这样做。 Otherwise you can use a UriBuilder, but you will still have to do some of the parsing yourself. 否则你可以使用UriBuilder,但你仍然需要自己进行一些解析。 There are some utility classes online as well, but I've never used them so I don't know how well they work: 网上还有一些实用工具类,但我从未使用它们,所以我不知道它们的工作情况如何:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM