ASP.NET:URI 处理
我正在编写一个方法,假设给定 1
和 hello
应该返回 http://something.com/?something=1&hello=en
。
我可以很容易地将其组合在一起,但是 ASP.NET 3.5 为构建 URI 提供了什么抽象功能?我想要这样的东西:
URI uri = new URI("~/Hello.aspx"); // E.g. ResolveUrl is used here
uri.QueryString.Set("something", "1");
uri.QueryString.Set("hello", "en");
return uri.ToString(); // /Hello.aspx?something=1&hello=en
我发现 Uri
类听起来非常相关,但我找不到任何真正执行上述操作的东西。有什么想法吗?
(就其价值而言,参数的顺序对我来说并不重要。)
I'm writing a method which, let's say, given 1
and hello
should return http://something.com/?something=1&hello=en
.
I could hack this together pretty easily, but what abstraction functionality does ASP.NET 3.5 provide for building URIs? I'd like something like:
URI uri = new URI("~/Hello.aspx"); // E.g. ResolveUrl is used here
uri.QueryString.Set("something", "1");
uri.QueryString.Set("hello", "en");
return uri.ToString(); // /Hello.aspx?something=1&hello=en
I found the Uri
class which sounds highly relevant, but I can't find anything which does the above really. Any ideas?
(For what it's worth, the order of the parameters doesn't matter to me.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
编辑以纠正大量错误的代码
基于这个答案对于类似的问题,您可以轻松地执行以下操作:
这也将对集合进行urlencode,因此:
将输出:
Edited to correct massively incorrect code
Based on this answer to a similar question you could easily do something like:
This will also urlencode the collection, so:
Will output:
到目前为止我对这里一无所知。所以每个人都有自己的实现。
示例来自 LinqToTwitter。
更新:
您还可以创建扩展方法:
和用法:
请注意,这里的所有内容都未经测试。
As far I know nothing here. So everybody has its own implementation.
Example from LinqToTwitter.
UPDATE:
You can also create extension method:
And usage:
Please note that everything here is untested.
只是合并答案=>
半成品代码。但应该工作得足够好。
Just combined answers=>
Half baked code. But should work well enough.
还有 UriBuilder 类
There's also the UriBuilder class
这可能会吸引你——最近在工作中我正在寻找一种“输入”常用的 URL 查询字符串变量的方法,因此开发了这个接口:
然后你可以实现这个接口来描述一个查询字符串参数,这样的实现您的“Hello”参数可能如下所示:
我开发了一个小型(非常非常基本)类来帮助使用这些强类型参数构建 URL:
This is something that might appeal to you- recently at work I was looking at a way to "type" commonly used URL query string variables and so developed this interface:
You can then implement this interface to describe a query string parameter, such an implementation for your "Hello" param might look like this:
I developed a small (and very, very basic) class to help build URLs using these strongly typed parameters:
这是我的版本(需要在 Select 上调用 .NET4 或 ToArray() )
我认为使用 Dictionary 可能意味着可以对项目进行重新排序,但这实际上似乎并没有在此处的实验中发生 - 不确定那是什么意思。
Here's my version (needs .NET4 or a ToArray() call on the Select)
I thought the use of Dictionary might mean the items can get reordered, but that doesn't actually seem to be happening in experiments here - not sure what that's about.