ASP.NET:URI 处理

标签 asp.net query-string uri

我正在编写一个方法,假设给定 1hello应该返回 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听起来高度相关的类(class),但我找不到任何真正做到上述内容的类(class)。有任何想法吗?

(对于它的值(value),参数的顺序对我来说并不重要。)

最佳答案

编辑以纠正大量不正确的代码

基于 this answer对于类似的问题,您可以轻松地执行以下操作:

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 

关于ASP.NET:URI 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1748609/

相关文章:

node.js - 在 NodeJS 查询字符串和请求模块中传递重音字符

c# - ASP.NET - 基于动态内容生成网页

c# - 从基本 URI 和相对路径创建新的 URI - 斜线有区别吗?

android - Uri.parse() 在单元测试中总是返回 null

java - 无法弄清楚 URIException

c# - 等同于 PHP 的 header 包括

asp.net - 将 [requireSSL ="true"] 放入我的 web.config 返回垃圾页面

c# - Hangfire - 没有为此对象定义无参数构造函数

javascript - ASP.net MVC 在登录时运行 Javascript 函数

c# - 如何在 asp.net 中使用 javascript 从代码后面添加 Querystring 参数?