如果在操作方法上也指定了操作过滤器,我想立即从操作过滤器返回,因为它是连接到控制器的结果。目标是允许我在必要时在操作方法级别覆盖控制器操作过滤器。
如果我创建了2个单独的动作过滤器并且在执行之前对动作方法进行了控制器特定版本检查,那么我可以这样做。如果可能的话,我宁愿避免创建两种类型。
答案 0 :(得分:1)
对于ASP.NET Core 1.1
var currentFilter = filterContext.ActionDescriptor
.FilterDescriptors
.Select(filterDescriptor => filterDescriptor)
.FirstOrDefault(filterDescriptor => ReferenceEquals(filterDescriptor.Filter, this));
if (currentFilter == null)
{
return;
}
if (currentFilter.Scope == FilterScope.Action)
{
//...
}
if (currentFilter.Scope == FilterScope.Controller)
{
//...
}
答案 1 :(得分:0)
您可以从action属性访问Filter
对象,然后检查范围:
[ControllerScope]
public class HomeController : Controller
{
[ControllerScope]
public ActionResult Index()
{
return View();
}
}
public class ActionScopeAttribute : ActionFilterAttribute
{
}
public class ControllerScopeAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var filters = FilterProviders.Providers.GetFilters(filterContext.Controller.ControllerContext,
filterContext.ActionDescriptor)
.ToList();
var filter = filters.First(f => f.Instance is ControllerScopeAttribute);
if (filter.Scope == FilterScope.Action)
{
//your logic
}
if (filter.Scope == FilterScope.Controller)
{
//your logic
}
}
}