测试属性是否在Controller或Action上

时间:2011-04-02 04:22:54

标签: asp.net-mvc custom-attributes

当属性触发时,我可以测试是否在Controller或Action上设置了吗?

我想要的行为是:如果存在则使用Action属性,否则使用Controller属性。像这样:

public class TestAttribute : FilterAttribute, IAuthorizationFilter
{
    public TestAttribute(string optionalParam = "") { /*...*/ }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        bool isClassAttribute; // = ????

        bool hasActionAttribute = filterContext.ActionDescriptor.GetCustomAttributes(typeof(TestAttribute ), false).Length > 0;

        if (isClassAttribute && hasActionAttribute)
            return; // handle in Action attribute
        else
            ; // do stuff with optionalParam...
    }
}

[TestAttribute]
public class TestClass 
{    
    [TestAttribute(optionalParam:"foo"]
    public ActionResult TestMethod() { return null; }    
}

我可以使用Order属性执行此操作,但不希望每次都设置它(或get funky)。

编辑/解决方案

好的,找到了我的问题的解决方案(但不是问题) - 设置属性基础参数AllowMultiple = false意味着last instance of the same filter type is allowed, and all others are discarded(并且Controller属性首先运行(?)所以应该很好... )。

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class TestAttribute : FilterAttribute, IAuthorizationFilter
{
    public TestAttribute(string optionalParam = "") { /*...*/ }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        // this should be the Action attribute (if exists), else the Controller attribute...
    }
}

无论如何我问了一个稍微不同的问题,所以仍然会给出答案分数;)

1 个答案:

答案 0 :(得分:0)

我相信该项目在每个方法调用上都会执行,但您可以参考:

public void OnActionExecuting(ActionExecutingContext filterContext) { }
..
..

string controllerName = filterContext.Controller.GetType().Name;
//either or:
string actionMethodName = filterContext.ActionDescriptor.ActionName;
string actionMethodName = filterContext.RouteData.Values["action"].ToString();

如果你的actionMethodName为null,那么它可能来自你的控制器 - 尽管就像我说的那样,只有当一个动作方法被调用时它们才会被调用(虽然测试了上面的代码,但不是100%肯定)应该回答你的问题)

希望有所帮助:)

相关问题