ASP.NET MVC - 在ActionFilter访问控制器属性 [英] ASP.NET MVC - Access a controller property in an ActionFilter

查看:232
本文介绍了ASP.NET MVC - 在ActionFilter访问控制器属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用统一实例化一个新的类到控制器构造函数和保存注入的类在控制器内的属性。然后我想用一个ActionFilter,看是否注入类有一些属性我把它的构造函数中进行验证。那么,有没有使用一个ActionFilter来validade注入类的属性的方式?

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?

在此先感谢

推荐答案

事情是这样的:

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

这篇关于ASP.NET MVC - 在ActionFilter访问控制器属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆