Today, I suddenly think of a method to determine whether a session is valid. In asp.net, our previous method is as follows:
| The code is as follows: |
Copy code |
|
If (Session ["UserID"] = "" | Session ["UserID"] = null)
{
Response. Redirect (".../Login. aspx? M = Login has timed out. Please log in again! ");
} |
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:
| The code is as follows: |
Copy code |
|
/// <Summary>
/// Determine whether the logon is successful. If the logon succeeds, the string stored in the session is returned. Otherwise, it is a null string.
/// </Summary>
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:
| The code is as follows: |
Copy code |
|
If (string. IsNullOrEmpty (isLogin (Session ["UserID"])
{
Response. Redirect (".../Login. aspx? M = Login has timed out. Please log in again! ");
} |
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:
| The code is as follows: |
Copy code |
|
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.
| The code is as follows: |
Copy code |
User _ user = isLogin (Session ["UserID"]);
If (_ user. UserID =-1)
{
// Logon failed
} |
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