2

In the view, for example, in "_Layout.cshtml"

How to get the controller/action which called this view?

After found the controller/action name, then how to get the list of the attribute it has? Or test if it has an attribute?

Thanks.

Eric Yin
  • 8,737
  • 19
  • 77
  • 118
  • First part of your question answered here: http://stackoverflow.com/questions/1083774/getting-the-name-of-the-controller-and-action-method-in-the-view-in-asp-net-mvc – David Spence Dec 04 '11 at 01:53
  • Do you want the action\controller attributes? see this answer of the action attributes: stackoverflow.com/a/8369591/601179 – gdoron Dec 04 '11 at 09:55

2 Answers2

9

@ViewContext.Controller will give you the controller instance that returned this view. Once you get the instance, you get the type and once you have the type you get into Reflection to get the attributes this type is decorated with. Writing a custom HTML helper to perform this job could be worth it:

public static class HtmlExtensions
{
    public static bool IsDecoratedWithFoo(this HtmlHelper htmlHelper)
    {
        var controller = htmlHelper.ViewContext.Controller;
        return controller
            .GetType()
            .GetCustomAttributes(typeof(FooAttribute), true)
            .Any();
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1. You don't check the action attributes, only the controller. 2. It's better to use the `IsDefined` Method: http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.isdefined.aspx – gdoron Dec 04 '11 at 09:37
  • 3
    1. That's what he asked about. 2. You are correct, `IsDefined` is better. – Darin Dimitrov Dec 04 '11 at 09:38
  • Well he mentioned it in the body of the question, though in the title he asked for the controller. – gdoron Dec 04 '11 at 09:54
0

Since this is the first result in google even when searching for ASP.NET Core version, here's how to do this in .NET Core: Checking for an attribute in an action filter (please upvote original thread)

        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;
    }
kurdemol94
  • 358
  • 5
  • 12