【问题标题】:How to know if Controller has an Attribute or not in ASP.net?如何知道控制器是否在 ASP.net 中具有属性?
【发布时间】:2020-03-13 17:20:08
【问题描述】:

在视图中,例如在“_Layout.cshtml”中

如何获取调用该视图的控制器/动作?

找到控制器/动作名称后,如何获取它所具有的属性列表?或者测试一下有没有属性?

谢谢。

【问题讨论】:

标签: asp.net-mvc view attributes controller action


【解决方案1】:

@ViewContext.Controller 将为您提供返回此视图的控制器实例。一旦你得到了实例,你就得到了类型,一旦你有了类型,你就可以进入反射来获取这个类型所装饰的属性。编写一个自定义 HTML 助手来执行这项工作可能是值得的:

public static class HtmlExtensions
{
    public static bool IsDecoratedWithFoo(this HtmlHelper htmlHelper)
    {
        var controller = htmlHelper.ViewContext.Controller;
        return controller
            .GetType()
            .GetCustomAttributes(typeof(FooAttribute), true)
            .Any();
    }
}

【讨论】:

  • 1.您不检查动作属性,只检查控制器。 2.最好使用IsDefined方法:msdn.microsoft.com/en-us/library/…
  • 1.他就是这么问的。 2.你说得对,IsDefined更好。
  • 好吧,他在问题的正文中提到了它,尽管在标题中他要求控制器。
【解决方案2】:

由于即使在搜索 ASP.NET Core 版本时,这也是谷歌中的第一个结果,以下是在 .NET Core 中执行此操作的方法:Checking for an attribute in an action filter(请为原始线程投票)

        if (controllerActionDescriptor != null)
    {
        // Check if the attribute exists on the action method
        if (controllerActionDescriptor.MethodInfo?.GetCustomAttributes(inherit: true)?.Any(a => a.GetType().Equals(typeof(CustomAttribute))) ?? false)
            return true;

        // Check if the attribute exists on the controller
        if (controllerActionDescriptor.ControllerTypeInfo?.GetCustomAttributes(typeof(CustomAttribute), true)?.Any() ?? false)
            return true;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多