我正在写一个方法,比方说,给定1
and hello
应该返回http://something.com/?something=1&hello=en
.
I could将它们组合在一起非常容易,但是 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
听起来非常相关的类,但我找不到真正执行上述操作的任何内容。有任何想法吗?
(就其价值而言,参数的顺序对我来说并不重要。)
编辑以纠正大量不正确的代码
基于这个答案对于类似的问题,您可以轻松地执行以下操作:
UriBuilder ub = new UriBuilder();
// You might want to take more care here, and set the host, scheme and port too
ub.Path = ResolveUrl("~/hello.aspx"); // Assumes we're on a page or control.
// Using var gets around internal nature of HttpValueCollection
var coll = HttpUtility.ParseQueryString(string.Empty);
coll["something"] = "1";
coll["hello"] = "en";
ub.Query = coll.ToString();
return ub.ToString();
// This returned the following on the VS development server:
// http://localhost/Hello.aspx?something=1&hello=en
这也将对集合进行 urlencode,因此:
coll["Something"] = "1";
coll["hello"] = "en&that";
将输出:
Something=1&hello=en%26that
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)