views:

175

answers:

1

Hello

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

+1  A: 

Something like this?:

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

        if (yourController == null)
        {
            throw 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 InvalidOperationException("There is no YourProperty !!!");
        }
    }
}
eu-ge-ne
thanks skaffman. The thing is the filter will be in every controller but not all of them will have the property defined. So I have to look to see if it exists in the current controller and then check the value if it does :)...
Andre da Silva Carrilho
The easiest way to do this would be to make an IContainsYourProperty interface (with a single YourProperty property) and have controllers which expose this property implement the interface, then the filter can check for the existence of this interface on the controller. Otherwise, use Reflection to check for the property, but this is probably overkill.
Levi
That was what I ended up doing. Thanks Levi :)
Andre da Silva Carrilho