Today suddenly thought of a judge session is legitimate practice, asp.net, before our approach is the following form:
copy Code code as follows:
if (session["UserID"] = = "" | | session["UserID"] = = null)
{
Response.Redirect (".. /login.aspx?m= Login has timed out, please login again! ");
}
I always thought this method is very bad, very bad, but has not found a good way, just suddenly thought and anonymous method, combined?? operator, if the session is empty, then it is not legal and can be used to determine whether the user is logged in.
Because session["UserID" returns the object type, if it is empty, it will report null pointer exception, in the form of the above, and, this judgment of the behavior of the login state, in some projects is almost every page needs to use, so you can extract a method, Put it in a class with other public static methods, written in the following form:
Copy Code code as follows:
///<summary>
///to determine whether the login is successful, if successful, return the session stored string, otherwise an empty string
///</summary>
public static Func<object, string> IsLogin = Sessions => session As String?? String. Empty;
The object that can be stored in the session, so it can be a string, it can be a number, it can be a class or a collection. My code above assumes that a string is stored, and when invoked, it's like invoking the method, which calls this anonymous method:
Copy Code code as follows:
if (string. IsNullOrEmpty (IsLogin (session["UserID"))
{
Response.Redirect (".. /login.aspx?m= Login has timed out, please login again! ");
}
You can say why not use a string directly. IsNullOrEmpty to directly judge the session? So I tell you this, if this key is not judged by you in the session, it will report the null pointer exception directly.
What if it's a class? It is also obvious that the session store, for example, is a user class, so the face code changes to this form:
Copy Code code as follows:
public static Func<object, user> IsLogin = Sessions => session as User?? New User () {UserID =-1};
Because the returned type is user, you can use a user class to receive the returned value, which can be used directly in subsequent operations.
Copy Code code as follows:
User _user = IsLogin (session["UserID"));
if (_user. UserID = = 1)
{
//Login failed
}
I don't know if that's a good idea, but I think it's easier for me to read the code, and it will be easy to operate. If you have a better way, please feel free.