2 {
3 Response.Redirect (".. /login.aspx?m= Login has timed out, please re-login! ");
6?
Always I think this method is very bad, very bad, but has not found a good method, just suddenly thought and anonymous method, combined?? operator, if the session is empty, then it is illegal and can be used to determine whether the user is logged in.
Because session["UserID" returned is the type of object, if it is empty, it will be reported null pointer exception, in the form of the above, and, this kind of judge the behavior of the login state, in some projects is almost every page needs to use, so you can extract a method, Put in a class with other public static methods, written as follows:
1//<summary>
2///Determines whether the login succeeds, or if successful, returns the string that is stored in the session, otherwise an empty string
3//</summary>
4 public static func<object, string> IsLogin = Session = Session As String?? String. Empty;
The object that can be stored in the session, so, can be a string, can be a number, or it can be a class or a collection. My above code assumes that the store is a string, called, as if it were called by the method that called the anonymous method:
1 if (string. IsNullOrEmpty (IsLogin (session["UserID")))
2 {
3 Response.Redirect (".. /login.aspx?m= Login has timed out, please re-login! ");
4}
You might say why not use string directly. IsNullOrEmpty to judge the session directly? So I'm telling you, this key that doesn't have your judgment in the session will directly report a null pointer exception.
What if it's a class? It is also obvious that the session stored for example a user class, then the face of the code is changed to this form:
1 public static func<object, user> IsLogin = Session = Session as User?? New User () {UserID =-1};
Because the returned type is user, a user class can be used to receive the returned value, so that it can be used directly in subsequent operations.
1 User _user = IsLogin (session["UserID"]);
2 if (_user. UserID = =-1)
3 {
4//Login failed
5}