【问题标题】:ActionFilterAttribute scope call orderActionFilterAttribute 范围调用顺序
【发布时间】:2015-05-18 08:21:01
【问题描述】:

我的 ActionFilter 的调用顺序有问题。

我创建了一个过滤器来设置布局 MasterName:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class MasterNameAttribute : ActionFilterAttribute
{
    public String MasterName { get; set; }

    public MasterNameAttribute(String masterName)
    {
        this.MasterName = masterName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        viewResult.MasterName = this.MasterName;

我在我的控制器中这样使用它:

[MasterName("_Layout_Main")]
public partial class ProjectController : BaseController
{        
    [MasterName("_Layout_Special")]
    public ActionResult Dashboard()
    {

不,我的问题是 ASP MVC 按顺序调用过滤器 Action-Scope -> Method-Scope。但我希望 Method-Scope 过滤器是结果并覆盖 Controller-Scope 过滤器。

我的问题:

  1. 在 MSDN 中写道,过滤器是按“AttributeTargets”枚举(类 = 4,方法 = 0x40)的枚举值顺序调用的。为什么最后调用的是 Controller-Scope 过滤器?
  2. 如何在不使用“订单”属性的情况下解决订单问题? 是否存在检测 samt 类型的 Methode-Scope 过滤器是否存在的正确方法?

提示

.ControllerDescriptor.IsDefined(...

对我没有帮助,因为如果 MasterName 是否由过滤器设置,我的实际实现有一些条件。因此,查找 Method-Scope 属性并不能告诉我是否使用了过滤器以及是否应该使用 Controller-Scope 过滤器(仅在未使用 Method-Scope 过滤器的情况下)。所以我认为适当的调用顺序将是最好的解决方案。

与@swapneel answere 相关:

抱歉,这不符合我的需求。我有一个非常复杂的布局选择,最好由属性设置。我需要继承、覆盖和排序逻辑。

喜欢:

[MasterName("_Layout1", Host = "sub1.domain.com")]
[MasterName("_Layout2", Host = "sub2.domain.com")]
[MasterName("_Layout3", Host = "sub3.domain.com")]
public partial class ProjectController : BaseController
{
    [MasterName("_Layout_1_1", Host = "sub1.domain.com")]
    [MasterName("_Layout_2_1", Host = "sub2.domain.com")]
    public ActionResult Dashboard()
    {

此处,主机“sub2.domain.com”的“仪表板”操作调用应使用“_Layout2_1”覆盖控制器定义的“_Layout2”MasterName。在所有其他操作中,它不会被覆盖,并且“_Layout2”是活动的。

向史蒂芬致敬!

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-5 actionfilterattribute


    【解决方案1】:

    这可能与您的问题无关,但我认为

    如果您想在运行时为每个视图设置一个或不同的母版页 时间或设计时间。你可以使用_ViewStart.cshtml.


    _ViewStart.cshtml 文件将在每个视图的渲染开始时执行。此文件中代码块中包含的任何代码都将在视图中的任何代码之前执行。通常,此文件将设置应用程序中的视图使用的布局模板:

    @{
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    

    一个 MVC 应用程序可以有多个 _ViewStart.cshtml 文件。这些文件的执行顺序取决于文件在文件夹层次结构中的位置以及正在呈现的特定视图。 MVC 运行时将首先执行位于 Views 文件夹根目录下的 _ViewStart.cshtml 文件中的代码。然后它将沿着文件夹层次结构向上工作,执行沿途找到的每个_ViewStart.cshtml 文件中的代码。例如,如果我们在以下位置有_ViewStart.cshtml 文件:

    从这个链接复制上面的文字 - what-is-the-purpose-of-the-viewstartcshtml-file-and-how-is-it-used

    【讨论】:

    • 不抱歉,这没有帮助,请参阅扩展的初始问题以获取更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2018-06-20
    相关资源
    最近更新 更多