Given the action name, controller name and HTTP verb (GET, POST .. etc), is it possible to check whether the action has (ie. is decorated by) a specific action filter attribute?
Please note: The action and controller are not the current action and controller but can be any action and controller in the app.
Thanks!
You add a new action to a controller by adding a new method to the controller. For example, the controller in Listing 1 contains an action named Index() and an action named SayHello(). Both methods are exposed as actions.
To redirect the user to another action method from the controller action method, we can use RedirectToAction method.
ActionName attribute is an action selector which is used for a different name of the action method. We use ActionName attribute when we want that action method to be called with a different name instead of the actual name of the method.
I have answered my own question, that is very similar to this.
You will also need the http method
(that is GET, POST) to get the correct result, in addition to action and controller names.
This is the piece of the code that solves your problem:
var controllerFactory = ControllerBuilder.Current
.GetControllerFactory();
var controllerContext = @this.ControllerContext;
var otherController = (ControllerBase)controllerFactory
.CreateController(
new RequestContext(controllerContext.HttpContext, new RouteData()),
controllerName);
var controllerDescriptor = new ReflectedControllerDescriptor(
otherController.GetType());
var controllerContext2 = new ControllerContext(
new MockHttpContextWrapper(
controllerContext.HttpContext.ApplicationInstance.Context,
method),
new RouteData(),
otherController);
var actionDescriptor = controllerDescriptor
.FindAction(controllerContext2, actionName);
I had a similar problem where I needed to check if an action had a custom attribute.
public static IEnumerable<MyCustomAttribute> GetAttributes(string controllerName, string actionName)
{
var types = Assembly.GetExecutingAssembly().GetTypes();
var controllers = types.Where(t => (t.Name == controllerName));
var action = controllers.SelectMany(type => type.GetMethods().Where(a => a.Name == actionName)).FirstOrDefault();
return action.GetCustomAttributes<MyCustomAttribute>(true);
}
Credit to this SO answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With