当前位置: 代码网 > it编程>编程语言>Asp.net > Asp.net MVC中的Http管道事件为什么要以Application_开头(原因解析)

Asp.net MVC中的Http管道事件为什么要以Application_开头(原因解析)

2025年02月13日 Asp.net 我要评论
今天遇到一个问题,需要在api请求结束时,释放数据库链接,避免连接池被爆掉。按照以往的经验,需要实现ihttpmodule,具体不展开了。但是实现了ihttpmodule后,还得去web.config

今天遇到一个问题,需要在api请求结束时,释放数据库链接,避免连接池被爆掉。

按照以往的经验,需要实现ihttpmodule,具体不展开了。
但是实现了ihttpmodule后,还得去web.config中增加配置,这有点麻烦了,就想有没有简单的办法。

其实是有的,就是在global.asax.cs里面定义并实现 application_endrequest 方法,在这个方法里面去释放数据库连接即可,经过测试,确实能达到效果。
但是,为什么方法名必须是application_endrequest ?在这之前真不知道为什么,只知道baidu上是这么说的,也能达到效果。
还好我有一点好奇心,想搞清楚是怎么回事情,就把net framework的源码拉下来(其实源代码在电脑里面已经躺了n年了) 分析了一下,以下是分析结果。

省略掉前面n个调用
第一个需要关注的是 httpapplicationfactory.cs
从名字就知道,这是httpapplication的工厂类,大家看看gloabal.asax.cs 里面,是不是这样定义的

public class mvcapplication : system.web.httpapplication
{
.....
}

两者结合起来看,可以推测,httpapplicationfactory 是用来获取 mvcapplication 实例的,实际情况也是如此 上代码(来自httpapplicationfactory)

internal class httpapplicationfactory{
  internal const string applicationfilename = "global.asax"; //看到这里,就知道为什么入口文件是global.asax了,因为这里定义死了
  ...
  private void ensureinited() {
      if (!_inited) {
          lock (this) {
              if (!_inited) {
                  init();
                  _inited = true;
              }
          }
      }
  }
  private void init() {
      if (_customapplication != null)
          return;
      try {
          try {
              _appfilename = getapplicationfile();
              compileapplication();
          }
          finally {
              // always set up global.asax file change notification, even if compilation
              // failed.  this way, if the problem is fixed, the appdomain will be restarted.
              setupchangesmonitor();
          }
      }
      catch { // protect against exception filters
          throw;
      }
  }
  private void compileapplication() {
    // get the application type and appstate from the global file
    _theapplicationtype = buildmanager.getglobalasaxtype();
    buildresultcompiledglobalasaxtype result = buildmanager.getglobalasaxbuildresult();
    if (result != null) {
        // even if global.asax was already compiled, we need to get the collections
        // of application and session objects, since they are not persisted when
        // global.asax is compiled.  ideally, they would be, but since <object> tags
        // are only there for asp compat, it's not worth the trouble.
        // note that we only do this is the rare case where we know global.asax contains
        // <object> tags, to avoid always paying the price (vswhidbey 453101)
        if (result.hasapporsessionobjects) {
            getappstatebyparsingglobalasax();
        }
        // remember file dependencies
        _filedependencies = result.virtualpathdependencies;
    }
    if (_state == null) {
        _state = new httpapplicationstate();
    }
    // prepare to hookup event handlers via reflection
    reflectonapplicationtype();
  }   
  private void reflectonapplicationtype() {
    arraylist handlers = new arraylist();
    methodinfo[] methods;
    debug.trace("pipelineruntime", "reflectonapplicationtype");
    // get this class methods
    methods = _theapplicationtype.getmethods(bindingflags.nonpublic | bindingflags.public | bindingflags.instance | bindingflags.static);
    foreach (methodinfo m in methods) {
        if (reflectonmethodinfoifitlookslikeeventhandler(m))
            handlers.add(m);
    }
    // get base class private methods (getmethods would not return those)
    type basetype = _theapplicationtype.basetype;
    if (basetype != null && basetype != typeof(httpapplication)) {
        methods = basetype.getmethods(bindingflags.nonpublic | bindingflags.instance | bindingflags.static);
        foreach (methodinfo m in methods) {
            if (m.isprivate && reflectonmethodinfoifitlookslikeeventhandler(m))
                handlers.add(m);
        }
    }
    // remember as an array
    _eventhandlermethods = new methodinfo[handlers.count];
    for (int i = 0; i < _eventhandlermethods.length; i++)
        _eventhandlermethods[i] = (methodinfo)handlers[i];
  }
  private bool reflectonmethodinfoifitlookslikeeventhandler(methodinfo m) {
    if (m.returntype != typeof(void))
        return false;
    // has to have either no args or two args (object, eventargs)
    parameterinfo[] parameters = m.getparameters();
    switch (parameters.length) {
        case 0:
            // ok
            break;
        case 2:
            // param 0 must be object
            if (parameters[0].parametertype != typeof(system.object))
                return false;
            // param 1 must be eventargs
            if (parameters[1].parametertype != typeof(system.eventargs) &&
                !parameters[1].parametertype.issubclassof(typeof(system.eventargs)))
                return false;
            // ok
            break;
        default:
            return false;
    }
    // check the name (has to have _ not as first or last char)
    string name = m.name;
    int j = name.indexof('_');
    if (j <= 0 || j > name.length-1)
        return false;
    // special pseudo-events
    if (stringutil.equalsignorecase(name, "application_onstart") ||
        stringutil.equalsignorecase(name, "application_start")) {
        _onstartmethod = m;
        _onstartparamcount = parameters.length;
    }
    else if (stringutil.equalsignorecase(name, "application_onend") ||
             stringutil.equalsignorecase(name, "application_end")) {
        _onendmethod = m;
        _onendparamcount = parameters.length;
    }
    else if (stringutil.equalsignorecase(name, "session_onend") ||
             stringutil.equalsignorecase(name, "session_end")) {
        _sessiononendmethod = m;
        _sessiononendparamcount = parameters.length;
    }
    return true;
  }
}

上面代码调用链路是ensureinited->init->compileapplication->reflectonapplicationtype->reflectonmethodinfoifitlookslikeeventhandler ,核心作用是:将mvcapplication中,方法名包含下划线、方法参数为空或者有2个参数(第一个参数的类型是object,第二个参数的类型是eventargs) 的方法加入到_eventhandlermethods 中
那么事件是怎么绑定的呢?继续上代码

internal class httpapplicationfactory{
......
  using (new applicationimpersonationcontext()) {
      app.initinternal(context, _state, _eventhandlermethods);
  }
......
......
  using (new applicationimpersonationcontext()) {
      app.initinternal(context, _state, _eventhandlermethods);
  }
......
}
// httpapplication.cs
public class httpapplication{
  internal void initspecial(httpapplicationstate state, methodinfo[] handlers, intptr appcontext, httpcontext context) {
    .....    
      if (handlers != null) {
          hookupeventhandlersforapplicationandmodules(handlers);
      }
    .....
  }
  internal void initinternal(httpcontext context, httpapplicationstate state, methodinfo[] handlers) {
    .....
      if (handlers != null)        
        hookupeventhandlersforapplicationandmodules(handlers);
    .....
  }
  private void hookupeventhandlersforapplicationandmodules(methodinfo[] handlers) {
      _currentmodulecollectionkey = httpapplicationfactory.applicationfilename;
      if(null == _pipelineeventmasks) {
          dictionary<string, requestnotification> dict = new dictionary<string, requestnotification>();
          buildeventmaskdictionary(dict);
          if(null == _pipelineeventmasks) {
              _pipelineeventmasks = dict;
          }
      }
      for (int i = 0; i < handlers.length; i++) {
          methodinfo appmethod = handlers[i];
          string appmethodname = appmethod.name;
          int nameposindex = appmethodname.indexof('_');
          string targetname = appmethodname.substring(0, nameposindex);
          // find target for method
          object target = null;
          if (stringutil.equalsignorecase(targetname, "application"))
              target = this;
          else if (_modulecollection != null)
              target = _modulecollection[targetname];
          if (target == null)
              continue;
          // find event on the module type
          type targettype = target.gettype();
          eventdescriptorcollection events = typedescriptor.getevents(targettype);
          string eventname = appmethodname.substring(nameposindex+1);
          eventdescriptor foundevent = events.find(eventname, true);
          if (foundevent == null
              && stringutil.equalsignorecase(eventname.substring(0, 2), "on")) {
              eventname = eventname.substring(2);
              foundevent = events.find(eventname, true);
          }
          methodinfo addmethod = null;
          if (foundevent != null) {
              eventinfo reflectionevent = targettype.getevent(foundevent.name);
              debug.assert(reflectionevent != null);
              if (reflectionevent != null) {
                  addmethod = reflectionevent.getaddmethod();
              }
          }
          if (addmethod == null)
              continue;
          parameterinfo[] addmethodparams = addmethod.getparameters();
          if (addmethodparams.length != 1)
              continue;
          // create the delegate from app method to pass to addxxx(handler) method
          delegate handlerdelegate = null;
          parameterinfo[] appmethodparams = appmethod.getparameters();
          if (appmethodparams.length == 0) {
              // if the app method doesn't have arguments --
              // -- hookup via intermidiate handler
              // only can do it for eventhandler, not strongly typed
              if (addmethodparams[0].parametertype != typeof(system.eventhandler))
                  continue;
              arglesseventhandlerproxy proxy = new arglesseventhandlerproxy(this, appmethod);
              handlerdelegate = proxy.handler;
          }
          else {
              // hookup directly to the app methods hoping all types match
              try {
                  handlerdelegate = delegate.createdelegate(addmethodparams[0].parametertype, this, appmethodname);
              }
              catch {
                  // some type mismatch
                  continue;
              }
          }
          // call the addxxx() to hook up the delegate
          try {
              addmethod.invoke(target, new object[1]{handlerdelegate});
          }
          catch {
              if (httpruntime.useintegratedpipeline) {
                  throw;
              }
          }
          if (eventname != null) {
              if (_pipelineeventmasks.containskey(eventname)) {
                  if (!stringutil.stringstartswith(eventname, "post")) {
                      _apprequestnotifications |= _pipelineeventmasks[eventname];
                  }
                  else {
                      _apppostnotifications |= _pipelineeventmasks[eventname];
                  }
              }
          }
      }
  }
}

核心方法:hookupeventhandlersforapplicationandmodules,其作用就是将前面获取到的method与httpapplication的event进行绑定(前提是方法名是以application_开头的),

后面就是向iis注册事件通知了,由于看不到iis源码,具体怎么做的就不知道了。

最后安利一下,还是用net core吧,更加清晰、直观,谁用谁知道。

到此这篇关于asp.net mvc中的http管道事件为什么要以application_开头的文章就介绍到这了,更多相关asp.net mvc http管道事件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com