开发者

is static methods secure in asp.net

开发者 https://www.devze.com 2023-03-05 14:06 出处:网络
heys guys, i have a website, which contains lots of db work to display data on page, so i have created a VB class whi开发者_StackOverflow中文版ch is public, under App_Code.

heys guys, i have a website, which contains lots of db work to display data on page, so i have created a VB class whi开发者_StackOverflow中文版ch 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..


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:

  • Your connection is never closed, even after you're done using it.
  • You will have issues if you have multiple queries trying to use the connection at the same time.

So I recommend you use the following pattern to ensure your connections are only kept open as long as they are in use.

public void DoSomething()
{
    //Doing some work that doesn't need a connection.

    //Now ready to submit or fetch data from the database.
    using (SqlConnection connection = new SqlConnection(...))
    {
        using (SqlCommand command = new SqlCommand(..., connection))
        {
            //Now, working with the connection and command.
        }
    }

    //Done with the connection, doing more work now.
}

The using statement works with anything that is IDisposable. Your connection variable here will be automatically closed and destroyed at the closing bracket of the using statement. I recommend you use it for anything that you can. Streams, SqlConnections, Fonts, etc.


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

SELECT Col4 FROM Table2

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.'

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号