Asp.net Module原理

来源:互联网 发布:金勃良知乎 编辑:程序博客网 时间:2024/06/02 04:31

当一个请求从客户端发出,首先经过网络最近的节点,DNS,DNS解析为 IP:port

2.请求继续传播到反向服务器

3.请求到达服务器的http.sys服务。

4.http.sys服务把请求给IIS(或其他的服务)

5.IIS创建HttpRunTime 对象。HttpRunTime  创建HttpApplication.

6.HttpApplication 中有23个事件。这些事件的执行就是服务器的处理过程


7.23个事件依次执行。这些事件是空的,大部分只是空实例。 我们可以在这些事件上增加新的执行方法。这些新增的执行方法封装为模块,就是module. 一个module可以注册多个方法。

这个模块需要在webconfig 中注册。

每次请求都要执行这些事件住的的方法。 有些是没必要的,为了优化性能可以把某些module 移除,移除也是在WebConfig 中配置。

8.如果没有Mudule,请求没有任何反应。但是系统给我们预先制定了一些mudule,这些在C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config中定义,比如seesion 等。

  
            <add name="Session" type="System.Web.SessionState.SessionStateModule" />
            <add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule" />
            <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />

找到System.Web.SessionState.SessionStateModule类,这个继承了IHttpModule。我们自建的module也是这样继承的

IHttpModule约束了这个方法 public void Init(HttpApplication httpApplication)。

9找到SessionStateModule类的init方法

其中有这些:看到了吧

    app.ReleaseRequestState +new EventHandler(this.OnReleaseState);
    app.EndRequest +new EventHandler(this.OnEndRequest);

到这里模块就基本清楚了

-----------------------------------

下面验证一下

系统提供了这个模块UrlAuthorizationModule

到这个模块的源码  他的init只有一句话

public void Init(HttpApplication app)
        {
            app.AuthorizeRequest +new EventHandler(this.OnEnter);
        }

在OnEnter 方法中,如果验证不通过,会抛出401

internal static void ReportUrlAuthorizationFailure(HttpContext context, object webEventSource)
{
    context.Response.StatusCode = 401;
    UrlAuthorizationModule.WriteErrorMessage(context);
    if (context.User !null && context.User.Identity.IsAuthenticated)
    {
        WebBaseEvent.RaiseSystemEvent(webEventSource, 4007);
    }
    context.ApplicationInstance.CompleteRequest();
}




原创粉丝点击