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

问题描述 投票:1回答:2

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

这样的事情

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

   public class TestMethodAttribute : Attribute
   {
       public bool testParameters()
       {
          if(a==b)
            return false;
           else
             return false;
      }
   }
c# asp.net
2个回答
1
投票

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

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"
            }));
        }
    }
}

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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.