2

I want to build a custom filter attribute that will be added to controller level. How can I get the current controller, action and parameter names that are currently being invoked?

Example: If I issues a POST request to: https://localhost:443/api/users/delete/3

How can I get in my attribute (and I am not talking about url parsing here)

  • controller = users
  • action = delete
  • id = 3
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
user2818430
  • 5,853
  • 21
  • 82
  • 148
  • You want to create a Filter or an attribute? – Ramesh May 08 '15 at 06:56
  • @Ramesh Basically a filter attribute :) – user2818430 May 08 '15 at 06:57
  • @Kamo: seams the question there answers my first 2 questions related to controller and action. What about the id parameter? – user2818430 May 08 '15 at 07:13
  • @user2818430 - I don't have VS currently available but I believe in `filterContext` there is `RouteData` or something like this property which can provide additional informations about route values. – kamil-mrzyglod May 08 '15 at 07:15
  • Also see [Accessing post or get parameters in custom authorization MVC4 Web Api](http://stackoverflow.com/questions/12817202/accessing-post-or-get-parameters-in-custom-authorization-mvc4-web-api) for accessing GET and POST parameters. – CodeCaster May 08 '15 at 09:18

1 Answers1

3

@Kamo has provided duplicate question for the first parts, for the ID, use .ActionArguments, eg:

 public override void OnActionExecuting(HttpActionContext actionContext)
 {
     var id = (int)actionContext.ActionArguments["id"];

ActionArguments is a dictionary, so you could iterate using linq if the arg is optional or you are writing a generic handler for all your actions (eg to log every action with its parameters/arguments)

This is as provided by the framework, after binding, so will match the Action's parameters - if the binding does not match an action then your filterabbtribute won't kick in even if applied at the Controller level. You can't use this for finding why your routes don't match your actions.

freedomn-m
  • 27,664
  • 8
  • 35
  • 57