ASP.NET MVC - Access a controller property in an ActionFilter

user143662 picture user143662 · Jul 23, 2009 · Viewed 13k times · Source

I'm using Unity to instantiate a new class into the controller constructor and save the injected class in a property inside the controller. Then I want to use an ActionFilter to see if the injected class has some properties that I validate inside it's constructor. So is there a way to use an ActionFilter to validade the properties of the injected class?

Thanks in advance

Answer

eu-ge-ne picture eu-ge-ne · Jul 23, 2009

Something like this?:

public class ValidateActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var yourController = filterContext.Controller as YourController;

        if (yourController == null)
        {
            throw new InvalidOperationException("It is not YourController !!!");
        }

        // It is YourController - validate here
        var yourProperty = yourController.YourProperty;

        // UPDATED ***************************
        // or test whether controller has property

        var property = filterContext.Controller.GetType().GetProperty("YourProperty");

        if(property == null)
        {
            throw new InvalidOperationException("There is no YourProperty !!!");
        }
    }
}