如何创建一个停止调用方法的自定义属性

时间:2016-07-20 08:07:14

标签: c# asp.net

我想在c#上创建一个属性,该属性将在调用方法之前检查一些参数,如果出现错误则会停止调用该方法。

类似这样的事情

   [TestMethod]
   public void somemethod ()
   {
      .....
   }

   public class TestMethodAttribute : Attribute
   {
       public bool testParameters()
       {
          if(a==b)
            return false;
           else
             return false;
      }
   }

2 个答案:

答案 0 :(得分:1)

您必须继承 ActionFilterAttribute(System.Web.Mvc)类并重写OnActionExecuting方法。请记住,“OnActionExecuting”方法由ASP.NET MVC框架 调用 调用您执行的操作方法。

public class TestMethodIfLoggedIn : ActionFilterAttribute
   {
     public override void OnActionExecuting(ActionExecutingContext filterContext)
       {
         base.OnActionExecuting(filterContext);
         var a = HttpContext.Current.Session["a"];
         var b = HttpContext.Current.Session["b"];

       if(a.ToString() == b.ToString())
        { 
           HttpContext.Current.Session["Message"] = "A = B";
        }
     else    
         {
            HttpContext.Current.Session["Message"] = "A is not equal to b";
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "Desired_Controller_Name",
                action = "ActionName"
            }));
        }
    }
}

答案 1 :(得分:0)

如果您使用DI容器,例如Unity。您可以拦截方法调用。

install-package Unity.Interception

配置DI容器,如下所示:

UnityContainer container = new UnityContainer();
container.RegisterType<ICustomType, CustomType>(
   new InterceptionBehavior<PolicyInjectionBehavior>(),
   new Interceptor<InterfaceInterceptor>());

定义属性:

[AttributeUsage(AttributeTargets.Method)]
public class TestMethodAttribute : HandlerAttribute
{
    public override ICallHandler CreateHandler(IUnityContainer container)
    {
        return new TestMethodHandler();
    }
}

添加拦截逻辑:

public class TestMethodHandler : ICallHandler
{
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        //manipulate with method here 
        //getNext is a method delegate 
        IMethodReturn result = getNext()(input, getNext);
        return result;
    }
}