Static Methods in ASP.NET
i am a little confused about static methods within asp.net-pages. E.g. what if i create a static Database-Method to get Userdata out of the database (something like UserDBHandler.getUser()) - is it sa开发者_如何学运维fe 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.
Within the scope of a single session I believe that you will be running on a single thread so this shouldn't be a problem.
It depends on how the method is written. If the method is written in a thread safe manner, then you should have no problems.
精彩评论