【问题标题】:Test if Attribute is on Controller or Action测试属性是在控制器还是动作上
【发布时间】:2011-07-28 03:03:11
【问题描述】:

当一个 Attribute 触发时,我可以测试是在 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 (并且控制器属性首先运行(?)所以应该很好去......)。

[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...
    }
}

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

【问题讨论】:

    标签: asp.net-mvc custom-attributes


    【解决方案1】:

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

    公共无效 OnActionExecuting(ActionExecutingContext filterContext) { } .. .. 字符串控制器名称 = filterContext.Controller.GetType().Name; //两者任一: 字符串 actionMethodName = filterContext.ActionDescriptor.ActionName; string actionMethodName = filterContext.RouteData.Values["action"].ToString();

    如果您的 actionMethodName 为空,那么它可能来自您的控制器 - 尽管就像我说的那样,它们可能仅在按原样调用操作方法时才被调用(虽然测试了上面的代码并且这不是 100% 确定的)应该回答你的问题)

    希望对你有帮助:)

    【讨论】:

    • Thnaks Adam,但是对于控制器级别的属性也存在 ActionName 属性。
    猜你喜欢
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多