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.