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.
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.
@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();
}
}
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;
}