1

Let's say I've got an ActionFilterAttribute on an Action method in a Controller. This Action Filter exposes a couple public members (properties, in this case).

Is there any way from within the body of my Action method that I can access these public properties (read-only needed)?

1
  • Why would you want to do that? You can pass values to controller by setting context.Controller.ViewData values. Commented Feb 13, 2011 at 2:39

1 Answer 1

2

Attribute properties could be only constant values and must be known at compile time:

[MyActionFilter(Prop1 = "SomeProp1", Prop2 = "SomeProp2")]
public ActionResult SomeAction() 
{
    // use "SomeProp1" and "SomeProp2" here
    ...
}

so inside the action you already know those values as you have hardcoded them just above the action method signature. To avoid hardcoding magic strings in two different places of you program you could use constants:

public const string Prop1 = "SomeProp1";
public const string Prop2 = "SomeProp2";

and then:

[MyActionFilter(Prop1 = Constants.Prop1, Prop2 = Constants.Prop2)]
public ActionResult SomeAction() 
{
    // use Constants.Prop1 and Constants.Prop2 here
    ...
}

Of course you could always use reflection:

var myFilters = (MyActionFilterAttribute[])MethodInfo.GetCurrentMethod()
    .GetCustomAttributes(typeof(MyActionFilterAttribute), false);
if (myFilters.Length > 0)
{
    var prop1 = myFilters[0].Prop1;
    var prop2 = myFilters[0].Prop2;
}

but IMHO that would be a great waste so don't do it :-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.