只是想知道,谷歌搜索如何在asp mvc 4中使用过滤器。我发现有些人像这样定义它们:
public class CustomFilter : ActionFilterAttribute
有些人喜欢这样:
public class CustomFilter : ActionFilterAttribute, IActionFilter
ActionFilterAttribute已经覆盖了所有操作,为什么我也应该实现这个接口?
另外例如在下一个代码中,最后再次调用过滤器,为什么会这样?
public class
CustomActionFilter : ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
// TODO: Add your acction filter's tasks here
// Log Action Filter Call
MusicStoreEntities storeDB = new MusicStoreEntities();
ActionLog log = new ActionLog()
{
Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
Action = filterContext.ActionDescriptor.ActionName + " (Logged By: Custom
Action Filter)",
IP = filterContext.HttpContext.Request.UserHostAddress,
DateTime = filterContext.HttpContext.Timestamp
};
storeDB.ActionLogs.Add(log);
storeDB.SaveChanges();
this.OnActionExecuting(filterContext);
}
}
答案 0 :(得分:2)
如果您检查MSDN definition of ActionFilterAttribute ,您将看到它是一个继承接口 IActionFilter AND IResultFilter 的抽象类。
实际上继承自 ActionFilterAttribute ,
public class CustomFilter : ActionFilterAttribute
相当于继承类 FilterAttribute 和接口 IActionFilter 和 IResultFilter
public class CustomFilter : FilterAttribute, IActionFilter, IResultFilter
与
无异public class CustomFilter : ActionFilterAttribute, IActionFilter, IResultFilter
因此,继承自 ActionFilterAttribute 与继承 ActionFilterAttribute 和 IActionFilter 无异。