【问题标题】:MVC Get ActionFilterAttribute value in Base Controller OnActionExecutingMVC 在基本控制器 OnActionExecuting 中获取 ActionFilterAttribute 值
【发布时间】:2011-06-28 21:41:24
【问题描述】:

如果我在继承 BaseController 的控制器中的操作上设置属性,是否可以在某些 BaseController 函数中获取该值?

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {  ....  want to get the value of DoNotLockPage attribute here?  }



public class CompanyAccountController : BaseController
{
        [DoNotLockPage(true)]
        public ActionResult ContactList()
        {...

【问题讨论】:

    标签: asp.net-mvc actionfilterattribute onactionexecuting


    【解决方案1】:

    采取了不同的路线。 我可以简单地在 basecontroller 中创建一个变量,并在任何操作中将其设置为 true。 但我想使用一个属性,只是更容易理解代码。 基本上在基本控制器中,我有代码可以在某些条件下锁定页面,仅查看。 但是在基类中这会影响每个页面,我需要始终将几个操作设置为编辑。

    我向基本控制器添加了一个属性。 在属性的 OnActionExecuting 中,我能够获取当前控制器并将其属性设置为 true。

    这样我就能够在我的 ViewResult 覆盖中获取我的属性设置。

    我的属性

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    public sealed class DoNotLockPageAttribute : ActionFilterAttribute
    {
        private readonly bool _doNotLockPage = true;
    
        public DoNotLockPageAttribute(bool doNotLockPage)
        {
            _doNotLockPage = doNotLockPage;
        }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var c = ((BaseController)filterContext.Controller).DoNotLockPage = _doNotLockPage;
        }
    }
    

    我的基本控制器

    public class BaseController : Controller
    {
        public bool DoNotLockPage { get; set; } //used in the DoNotLock Attribute
    
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {  ......  }
    
        protected override ViewResult View(string viewName, string masterName, object model)
        {
            var m = model;
    
            if (model is BaseViewModel)
            {
                if (!this.DoNotLockPage) 
                { 
                    m = ((BaseViewModel)model).ViewMode = WebEnums.ViewMode.View; 
                }
                ....
                return base.View(viewName, masterName, model);
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 2013-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多