Ninject拦截MVC 3控制器

时间:2012-08-22 15:36:31

标签: asp.net asp.net-mvc-3 ninject interception

我使用Ninject Interceptions Extentions和Dynamic Proxy v3.0进行了拦截。我正在尝试类代理拦截MVC 3控制器。拦截控制器但行为不正确。 intereceptor只拦截对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();           
    } 

}

0 个答案:

没有答案