Today, I suddenly think of a method to determine whether a session is valid. In asp.net, our previous method is as follows:
1 if (Session ["UserID"] = "" | Session ["UserID"] = null)
2 {
3 Response. Redirect (".../Login. aspx? M = login has timed out. Please log in again! ");
4}
I have always thought that this method is very bad and very bad, but I have never found a good method. Just now I suddenly thought of how to combine it with the anonymous method ?? Operator. If the session is null, it is invalid and can be used to determine whether a user is logged on.
Because Session ["UserID"] returns the Object type, if it is null, a null pointer exception will be reported. In the preceding format, this behavior determines the logon status, in some projects, almost every page needs to be used. Therefore, you can extract a method and put it into a class together with other public static methods. The form is as follows:
1 /// <summary>
2 // determine whether the logon is successful. If the logon succeeds, the string stored in the session is returned. Otherwise, the string is null.
3 /// </summary>
4 public static Func <Object, string> isLogin = session => session as string ?? String. Empty;
The Object that can be stored in the Session. Therefore, it can be a string, a number, a class, or a set. The code above assumes that a string is stored, and the called method is like the one that calls this anonymous method:
1 if (string. IsNullOrEmpty (isLogin (Session ["UserID"])
2 {
3 Response. Redirect (".../Login. aspx? M = login has timed out. Please log in again! ");
4}
Why don't you use string. IsNullOrEmpty to directly judge the Session? So I will tell you, this will directly report a null pointer exception if the key in the Session does not have your judgment.
What if it is a class? Obviously, session storage is like a User class, so the above 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, you can use a User class to receive the returned value. In this way, you can directly use it in subsequent operations.
1 User _ user = isLogin (Session ["UserID"]);
2 if (_ user. UserID =-1)
3 {
4 // Logon Failed
5}
I don't know whether this method is good or not, but I think it is easier for me to read this code and to operate it conveniently. If you have a better method, please do not hesitate to advise.
From luacloud logs