我使用 Ninject Interceptions Extensions 和 Dynamic Proxy v3.0 进行拦截。我正在尝试类代理拦截 MVC 3 控制器。控制器被拦截但行为不正确。拦截器仅拦截对 ControllerBase 和 Controller 类上的公共虚拟方法的调用。我的 HomeController 公共虚拟方法永远不会被拦截。这是我的代码。我正在考虑使用 MVC 的过滤器来完成此任务,而不是 Ninject 拦截。
public class AuditAttribute : InterceptAttribute
{
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
return request.Context.Kernel.Get<AuditInterceptor>();
}
}
[Audit] //HomeController method not intercepted.
public virtual ActionResult Index()
{
return View();
}
public class AuditInterceptor : SimpleInterceptor
{
public AuditInterceptor(IAuditor auditor)
{
if (auditor == null)
throw new ArgumentNullException("auditor");
this.auditor = auditor;
}
protected override void OnError(IInvocation invocation, Exception exception)
{
stopWatch.Stop();
AuditEvent auditEvent = new AuditEvent();
auditEvent.ExceptionDescription = exception.Message;
auditEvent.FormName = string.Format("class: {0}, method: {1}", invocation.Request.Method.DeclaringType, invocation.Request.Method.Name);
auditEvent.AppName = appName;
this.auditor.WriteAudit(auditEvent);
auditEvent.LengthOfMethodCall = stopWatch.Elapsed;
base.OnError(invocation, exception);
}
protected override void AfterInvoke(IInvocation invocation)
{
stopWatch.Stop();
AuditEvent auditEvent = new AuditEvent();
auditEvent.ExceptionDescription = defaultExp;
auditEvent.FormName = string.Format("class: {0}, method: {1}", invocation.Request.Method.DeclaringType, invocation.Request.Method.Name);
auditEvent.AppName = appName;
auditEvent.LengthOfMethodCall = stopWatch.Elapsed;
this.auditor.WriteAudit(auditEvent);
}
protected override void BeforeInvoke(IInvocation invocation)
{
stopWatch.Start();
}
}