【发布时间】:2010-08-10 11:31:49
【问题描述】:
谁能告诉我两者之间有什么区别:
Request.QueryString["id"] 和 Request["id"]
如果是,哪个更好用?
【问题讨论】:
标签: c# asp.net query-string
谁能告诉我两者之间有什么区别:
Request.QueryString["id"] 和 Request["id"]
如果是,哪个更好用?
【问题讨论】:
标签: c# asp.net query-string
Request["id"] 从 QueryString、Form、Cookies 或 ServerVariables 集合中获取值。文档中没有指定搜索它们的顺序,但是当您查看源代码时,您会发现它是它们被提及的顺序。
因此,如果您知道变量所在的位置(通常会这样做),最好使用更具体的选项。
【讨论】:
Request 集合是 QueryString 的超集,还有一些与当前请求相关的数据。
至于“更好” - 我建议您准确和明确(即使用 QueryString)以避免意外因素,当您得到意外结果只是意识到您使用了给定请求的密钥没有提供查询字符串值,但它存在于其他集合中。
【讨论】:
根据documentationHttpRequest索引器
查询字符串、表单、Cookie 或 ServerVariables 集合成员 在 key 参数中指定。
我更喜欢使用Request.QueryString["id"],因为它更明确了值的来源。
【讨论】:
Request.QueryString["id"] 查看每个 QueryString 传递的集合。 Request.Item["id"] 查看所有集合(QueryString、Form、Cookie 或 ServerVariables)。因此,应尽可能首选 QueryString 属性,因为它更小。
【讨论】:
根据 Reflector.Net,Request["id"] 定义为:
public string this[string key]
{
get
{
string str = this.QueryString[key];
if (str != null)
{
return str;
}
str = this.Form[key];
if (str != null)
{
return str;
}
HttpCookie cookie = this.Cookies[key];
if (cookie != null)
{
return cookie.Value;
}
str = this.ServerVariables[key];
if (str != null)
{
return str;
}
return null;
}
}
【讨论】:
HttpRequest.Item页)。我同意这是唯一合理的顺序,并且 是 暗示的,但是相信实现细节已经让我有足够的时间从那个错误中吸取教训 =)
Request.QueryString["id"] 将返回查询字符串中具有 id 键的项的值,而 Request["id"] 将返回来自 Request.QueryString、Request.Form、Request.Cookies 或Request.ServerVariables。
值得一提的是,Request.Item 的 documentation(这是您在调用 Request["id"] 时实际访问的内容)没有指定搜索集合的顺序,因此理论上您可能会收到不同的结果,具体取决于您运行的 asp.net 版本。
如果你知道你想要的值在你的查询字符串中,最好使用Request.QueryString["id"]来访问它,而不是Request["id"]。
【讨论】: