Preface
When implementing your own Handler, you only need to inherit the IHttpHandler interface. When using Session in Handler, you only need to inherit the IRequiresSessionState, why can I use the Session only after implementing the interface? We will discuss it with you below.
Tools
Reflector
Body
When Session is used in Handler, it is obtained from HttpContext. Then, use Reflector to directly find HttpContext and see how it is done. Use Reflector Disassembler to retrieve the entire class, directly search for the IRequiresSessionState keyword. Only one keyword is found in the entire class, and the position is 1157 rows. I will post the code below and you will understand it:
Public IHttpHandler Handler
{
Get
{
Return this. _ handler;
}
Set
{
This. _ handler = value;
This. RequiresSessionState = false;
This. ReadOnlySessionState = false;
This. InAspCompatMode = false;
If (this. _ handler! = Null)
{
If (this. _ handler is IRequiresSessionState)
{
This. RequiresSessionState = true;
}
If (this. _ handler is IReadOnlySessionState)
{
This. ReadOnlySessionState = true;
}
Page page = this. _ handler as Page;
If (page! = Null) & page. IsInAspCompatMode)
{
This. InAspCompatMode = true;
}
}
}
}
Code Description:
1. very critical code this. _ handler is IRequiresSessionState and this. _ handler is IReadOnlySessionState. Let's look at the description about IRequiresSessionState: specify that the target HTTP handler must have read and write access to the session status value. This. RequiresSessionState and this. ReadOnlySessionState are both false by default. That is to say, the Session data cannot be accessed by default. After you inherit the IRequiresSessionState or IReadOnlySessionState, the access permission is opened! As for where to open it, interested friends can continue to explore it and have more in-depth answers in the SessionStateModule class, it judges whether to enable Session access by accessing the attributes of this class.
End
This article has two purposes:
1. When I don't understand why, I must ask why, not only in this case, but I try my best to find out why.
2. Learn about this positive mode. Although I don't know which design mode it is, if it is mine, I may write a abstract to implement this function.
Tip: For Handler implementation, refer to the source code of HttpApplication.