c# – 从供应商的Global.asax继承Global.asax时不会触发Applicat
我正在尝试将代码添加到我没有源代码的第三方ASP.NET Web应用程序的application_start事件中.我是通过继承供应商的Global类来做到这一点的.这是代码(注意“new”关键字和对事件的基类版本的两次调用.这是因为基类方法不是抽象,虚拟或覆盖,我没有更改源代码) :
public class CustomGlobal : VendorNamespace.Global { new protected void Application_Start(object sender,EventArgs e) { var logName = "SPPCustom"; if (!System.Diagnostics.EventLog.SourceExists(logName)) System.Diagnostics.EventLog.CreateEventSource(logName,"Application"); var text = "Hello from Application Start!"; System.Diagnostics.EventLog.WriteEntry(logName,"Application started!"); File.WriteAllText(@"c:ApplicationStart.txt",text); Debug.WriteLine(text); base.Application_Start(sender,e); } new protected void Session_Start(object sender,EventArgs e) { var logName = "SPPCustom"; if (!System.Diagnostics.EventLog.SourceExists(logName)) System.Diagnostics.EventLog.CreateEventSource(logName,"Application"); System.Diagnostics.EventLog.WriteEntry(logName,"Session started!"); base.Session_Start(sender,e); } } 我在网站的global.asax文件中引用我的代码,如下所示: <%@ Application Codebehind="Global.asax.cs" Inherits="MyNamespace.CustomGlobal" Language="C#" %> Application_Start代码不会执行,但Session_Start代码会执行.我可以编写事件并从Session_Start写出文本文件但是Application_Start,nadda. 有谁知道这里发生了什么? 编辑: 这是执行Jan的建议后的代码: public CustomGlobal() { _global = new Global(); _appStartInfo = typeof(Global).GetMethod("Application_Start",BindingFlags.Instance | BindingFlags.NonPublic); _sessionStartInfo = typeof(Global).GetMethod("Session_Start",BindingFlags.Instance | BindingFlags.NonPublic); } protected void Application_Start(object sender,EventArgs e) { var logName = "SPPCustom"; if (!System.Diagnostics.EventLog.SourceExists(logName)) System.Diagnostics.EventLog.CreateEventSource(logName,"Application"); var text = "Hello Patient Portal from Application Start!"; System.Diagnostics.EventLog.WriteEntry(logName,"Application started!"); File.WriteAllText(@"c:PatientPortalApplicationStart.txt",text); Debug.WriteLine(text); //_sxaGlobal.ApplicationStart(sender,e); _appStartInfo.Invoke(_global,new[] {sender,e}); } } 现在它抛出以下错误: [NullReferenceException: Object reference not set to an instance of an object.] Global.Application_Start(Object sender,EventArgs e)28 [TargetInvocationException:调用目标抛出了异常.] [HttpException(0x80004005):调用目标抛出了异常.] [HttpException(0x80004005):调用目标抛出了异常.] 解决方法
这是继承问题.当使用new关键字时,调用CustomGlobal.Application_Start()将执行您的代码,但调用((HttpApplication)CustomGlobal).Application_Start()将执行供应商的代码.
解决方案可能是私人成员的模式 public class CustomGlobal : HttpApplication { private readonly VendorGlobal _global; private readonly MethodInfo _appStartInfo; public CustomGlobal() { _global = new VendorGlobal(); _appStartInfo = typeof(VendorGlobal).GetMethod("Application_Start",EventArgs e) { _appStartInfo.Invoke(_global,e}); // your custom code } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |