静态方法在 ASP.NET 中安全吗
嘿伙计们, 我有一个网站,其中包含大量用于在页面上显示数据的数据库工作,因此我在 App_Code 下创建了一个公共的 VB 类。
现在我拥有该类下的所有方法和函数都是共享(静态)的,而且我还有一个也是静态的连接变量。
客户抱怨,有时页面上会出现错误,其中一个错误是字段名称不属于表Table,我不明白,关于这一点,因为这种情况很少见,如果没有带有名称的字段,那么这个每次都应该发生,我的一位同事说不应该有共享方法或函数...这是正确的吗..
heys guys,
i have a website, which contains lots of db work to display data on page, so i have created a VB class which is public, under App_Code.
Now i have all the methods and functions under that class are Shared(Static), also i have a connection variable which is also static.
Client complains, that sometime there appears an error on the page, one of those error is Field Name does not belong to table Table, i dont understand, about this, as this is very rare, if there is no field with name, then this should occur everytime, one of my colleague says that there should not be Shared methods or functions... is this correct..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
静态方法不存在“安全”问题。你的同事很困惑。您编写的代码是否应该是静态方法或实例方法取决于它的具体用途。但将它们作为静态方法并不“危险”。
我建议您找出导致问题的查询,因为静态方法肯定不是问题所在。
就您的连接而言,我不建议将其保留为静态变量。我假设这是一个 SqlConnection 或类似的东西。在这种情况下,如果将其保留为静态变量,则可能会发生以下情况:
因此,我建议您使用以下模式来确保您的连接仅在使用时保持打开状态。
using 语句 适用于任何
IDisposable
。这里的connection
变量将在using
语句的右括号处自动关闭并销毁。我建议您尽可能使用它。Stream
、SqlConnection
、Font
等。There is no "security" problem with a static method. Your colleague is confused. Whether or not the code you wrote should be static or instance methods depends on what exactly it does. But having them as static methods is not "dangerous."
I suggest you track down the query that is causing the problem because the method being static is certainly not the issue.
As far as your connection goes, I would not recommend keeping it as a static variable. I assume this is a SqlConnection, or something similar. In that case, if you keep it as a static variable, it is possible for the following to occur:
So I recommend you use the following pattern to ensure your connections are only kept open as long as they are in use.
The using statement works with anything that is
IDisposable
. Yourconnection
variable here will be automatically closed and destroyed at the closing bracket of theusing
statement. I recommend you use it for anything that you can.Stream
s,SqlConnection
s,Font
s, etc.在我看来,您有一个不常用的 SQL 语句引用了表中不存在的列。
例如 - 假设您有像这样的 SQL
并且 Col4 不是 Table2 的成员。您会收到您所描述的错误。
如果您动态构建 SQL(这是狡猾的),您可能会遇到这种情况。
但我认为这与你的方法“安全性”没有任何关系。
It sounds to me like you have a infrequently-used SQL statement that refers to a column that does not exist on a table.
For example - suppose you had SQL like so
and Col4 was not a member of Table2. You would get the error you describe.
If you're building SQL dynamically (which is dodgey) you might run into this.
But I don't think it has anything to do with your method 'security.'