据我所知,每个动作过滤器都应该继承IActionFilter和FilterAttribute。 例如:
public class ActionSpeedProfilerAttribute : FilterAttribute, IActionFilter
{
public void OnActionExecuted(ActionExecutedContext filterContext)
{
throw new NotImplementedException();
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
throw new NotImplementedException();
}
}
http://www.dotnetcurry.com/aspnet-mvc/976/aspnet-mvc-custom-action-filter
但是在Microsoft的ASP.NET .Core教程中我们有没有FilterAttribute的例子:
public class SampleActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// do something before the action executes
}
public void OnActionExecuted(ActionExecutedContext context)
{
// do something after the action executes
}
}
https://docs.microsoft.com/pl-pl/aspnet/core/mvc/controllers/filters
我们应该继承FilterAttribute吗?
答案 0 :(得分:1)
如果您只想全局添加过滤器(FilterConfig
),则无需使用public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new SampleActionFilter());
}
}
,如下所示:
IActionFilter
...这将使每个操作都执行此过滤器,因为它实现了FilterAttribute
。
现在,如果您想创建一个可用于特定操作的过滤器,那么继承public class LogActionAttribute : FilterAttribute, IActionFilter
{
public void OnActionExecuted(ActionExecutedContext filterContext)
{
// log something about the action...
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
}
}
public class HomeController : Controller
{
[LogAction]
public ActionResult Index()
{
return View();
}
}
会更好,因为它允许您像这样使用它:
IResultFilter
因此,在这种情况下,您可以选择使用属性执行该过滤器的操作,而不是针对每个操作执行该操作。
作为旁注,还有一个IActionFilter
接口,其作用类似于IActionFilter
,它在执行结果时和执行结束后触发(同样public class LogActionAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
}
}
,但结果改为行动)。
这样做:
public class LogActionAttribute : FilterAttribute, IActionFilter, IResultFilter
{
public void OnActionExecuted(ActionExecutedContext filterContext)
{
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
}
public void OnResultExecuted(ResultExecutedContext filterContext)
{
}
public void OnResultExecuting(ResultExecutingContext filterContext)
{
}
}
与:
相同ActionFilterAttribute
...因为public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter
{
...
}
完全相同:
time = fields.Many2one('time.project', domain=lambda self: self._get_time())
vehicle_id = fields.Many2one('fleet.vehicle', 'Vehicle', required=True)
def _get_time(self):
vehicle_val = Get selected vehicle id from field vehicle_id on current form.
times = self.env['project.vehicle'].search([('vehicle_id', '=', vehicle_val)