我正在使用Unity将新类实例化到控制器构造函数中,并将注入的类保存在控制器内部的属性中。然后,我想使用ActionFilter来查看所注入的类是否具有一些在构造函数中验证的属性。那么有没有办法使用ActionFilter来验证注入的类的属性?

提前致谢

最佳答案

像这样吗?

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 !!!");
        }
    }
}

08-19 20:47