简体   繁体   中英

Static Methods in ASP.NET

i am a little confused about static methods within asp.net-pages. Eg what if i create a static Database-Method to get Userdata out of the database (something like UserDBHandler.getUser()) - is it safe to call that method from within web-pages? Isnt a new thread created for every page-call? And does HttpContext.Current always return the current-users context, so is it safe to call that from static methods to get the current-users session??

thanks

is it safe to call that method from within web-pages

Only if this method is reentrant . Example with sql:

public static User GetUser(string username)
{
    using (var connection = new SqlConnection(ConnectionString))
    using (var command = connection.CreateCommand())
    {
        connection.Open();
        command.CommandText = "select name, username from users where username = @username";
        command.Parameters.AddWithValue("@username", username);
        using (var reader = command.ExecuteReader()) 
        {
            while (reader.Read())
            {
                return new User 
                {
                    Username = username,
                    Name = reader.GetString(0),
                }
            }
        }
        return null;
    }
}

And call in your ASPX page:

var user = SomeClass.GetUser(Session["username"]);

And does HttpContext.Current always return the current-users context, so is it safe to call that from static methods to get the current-users session?

Yes, HttpContext.Current can be safely used to get the current HTTP context. But I would suggest you not calling HttpContext.Current in your DB access method. Just pass what is needed as argument so that your ASPX page when calling the method will safely read the session and pass the needed parameters.

Remark and personal advice: don't use static methods for data access. Calling code using static methods is close to impossible to unit test.

is it safe to call that method from within web-pages

That really depends on what you do in the method. This method should probably be a function without side-effects.

Isnt a new thread created for every page-call

Yes.

does HttpContext.Current always return the current-users context, so is it safe to call that from static methods to get the current-users session??

Yes.

If you want to be a purist though, it is not advisable to rely on static methods since they make your code hard to test in isolation. If class A calls a static method on class B, you will never be able to test class A without also testing / calling B.

在单个会话的范围内,我相信您将在单个线程上运行,因此这不应该是一个问题。

It depends on how the method is written. If the method is written in a thread safe manner, then you should have no problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM