【发布时间】: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 过滤器。
我的问题:
- 在 MSDN 中写道,过滤器是按“AttributeTargets”枚举(类 = 4,方法 = 0x40)的枚举值顺序调用的。为什么最后调用的是 Controller-Scope 过滤器?
- 如何在不使用“订单”属性的情况下解决订单问题?
是否存在检测 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