ASP.NET:使用 Request[“param”] 与使用 Request.QueryString[“param”] 或 Request.Form[“param”]
当从 ASP.NET 中的代码隐藏访问表单或查询字符串值时,使用以下命令有何优点和缺点:
// short way
string p = Request["param"];
而不是:
// long way
string p = Request.QueryString["param"]; // if it's in the query string or
string p = Request.Form["param"]; // for posted form values
我已经多次考虑过这个问题,并提出了:
Short way :
- 更短(更易读,新手更容易记住等)
长路:
- 如果表单值和查询字符串值具有相同的名称,则没有问题(尽管这通常不是问题)
- 后来阅读代码的人知道是否要查看 URL 或表单元素来查找数据源(可能是最重要的一点)
。
那么每种方法还有哪些其他优点/缺点?
When accessing a form or query string value from code-behind in ASP.NET, what are the pros and cons of using, say:
// short way
string p = Request["param"];
instead of:
// long way
string p = Request.QueryString["param"]; // if it's in the query string or
string p = Request.Form["param"]; // for posted form values
I've thought about this many times, and come up with:
Short way:
- Shorter (more readable, easier for newbies to remember, etc)
Long way:
- No problems if there are a form value and query string value with same name (though that's not usually an issue)
- Someone reading the code later knows whether to look in URLs or form elements to find the source of the data (probably the most important point)
.
So what other advantages/disadvantages are there to each approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
param 集合包括所有 (4) 个集合:
您可以争论在组合集合中进行搜索比查找特定集合要慢,但差异可以忽略不计
the param collection includes all (4) collections:
you can debate that searching in the combined collection is slower than looking into a specific one, but it is negligible to make a difference
长路更好,因为:
它可以更轻松地(稍后阅读代码时)找到值的来源(提高可读性)
它稍微快一点(尽管这通常不是'不重要,并且仅适用于首次访问)
在 ASP.NET 中(以及等效的PHP 中的概念),我总是使用您所说的“长形式”。我这样做的原则是,我想确切地知道我的输入值来自哪里,以便确保它们按照我期望的方式到达我的应用程序。因此,为了输入验证和安全性,我更喜欢更长的方式。另外,正如您所建议的,我认为可维护性值得多敲几下键盘。
The long way is better because:
It makes it easier (when reading the code later) to find where the value is coming from (improving readability)
It's marginally faster (though this usually isn't significant, and only applies to first access)
In ASP.NET (as well as the equivalent concept in PHP), I always use what you are calling the "long form." I do so out of the principle that I want to know exactly from where my input values are coming, so that I am ensuring that they get to my application the way I expect. So, it's for input validation and security that I prefer the longer way. Plus, as you suggest, I think the maintainability is worth a few extra keystrokes.