【问题标题】:Creating custom ActionFilterAttribute创建自定义 ActionFilterAttribute
【发布时间】:2014-07-25 09:31:38
【问题描述】:

我创建了一个名为 LayoutAttribute 的 ActionFilterAttribute 并将其添加到 ActionResult:

控制器:

    [Layout(PageType.Department,"dnr")]
    public ActionResult Kd(string mainBody, int dnr)
    {

布局属性:

using System.Web.Mvc;
using Komplett.Infrastructure.NInject;
using Ninject;


namespace Minion.Services.PageState
{
  public class LayoutAttribute : ActionFilterAttribute
  {
    private readonly PageType _pageType;
    private readonly string _pageIdName;

    public LayoutAttribute(PageType PageType,string PageIdName = "")
    {
        _pageType = PageType;
        _pageIdName = PageIdName;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var pageStateModel = KernelContainer.Kernel.Get<PageStateModel>();
        if (filterContext.ActionParameters.ContainsKey(_pageIdName ?? ""))
        {
            pageStateModel.PageId = (string)filterContext.ActionParameters[_pageIdName];
        }
        pageStateModel.PageType = _pageType;
    }
}

}

问题是永远不会调用 OnActionExecuting。 我也尝试在 global.asax.cs 中注册属性,但后来我需要一个无参数构造函数。我创建了它并将其添加到 global.asax.cs 中,如下所示:

GlobalFilters.Filters.Add(new LayoutAttribute());

这个,运气不好。

我做错了什么?如何让 MVC 调用 OnActionExecuting?

【问题讨论】:

  • 您不需要在全局过滤器中注册它。您确定在您的过滤器和重定向页面之前没有任何其他过滤器介入吗?
  • 使用属性,如stackoverflow.com/questions/4348071/… 所示。很可能不支持非默认构造函数。
  • 如果你把它放在控制器上会发生什么?

标签: c# asp.net-mvc-4


【解决方案1】:

确保您正在实施

System.Web.Mvc.ActionFilterAttribute

而不是

System.Web.Http.Filters.ActionFilterAttribute

它们都有 OnActionExecuting 和 OnActionExecuted 方法,所以可能有点欺骗

【讨论】:

    猜你喜欢
    • 2011-03-26
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2013-08-29
    相关资源
    最近更新 更多