zoukankan      html  css  js  c++  java
  • 说一说MVC的过滤器(一)

     在MVC项目中过滤器,最好把这些过滤器类放到一个文件夹中(Filters),然后过滤器文件的名称也是有规定的,格式应该为xxxAttribute,否则在控制器或控制器的方法中是无法进行调用过滤器的,在过滤器中需要继承FilterAttribute类,并且实现IActionFilter以及IResultFilter接口,这两个接口中实现的方法分别是OnActionExecuted,OnActionExecuting与OnResultExecuted,
    OnResultExecuting,前两个方法负责在相应开始和相应结束,而后两个方法负责结果发送开始以及结果发送结束,它们的执行顺序是:OnActionExecuting => OnActionExecuted => OnResultExecuting =>OnResultExecuted.在控制器添加过滤器标记时,过滤器的名字应该是[IsLogin],不需要带attribute,因为它是一种规范。
    现在搞一个案例,获取上下文的放到数据库,表格式:
    create table Log(
    content varchar(50) parmary key,
    logtime datetime2)
    我们在要在页面进行响应的时候进行记录日志,所以我们应在OnActionExecuted中进行操作代码如下:
    public class MyLoginAttribute : FilterAttribute, IActionFilter, IResultFilter
    {
    BookShopEntities book = new BookShopEntities();
    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
    // filterContext.HttpContext.Response.Write("OnActionExecuted");
    string cname = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;//控制器的名称
    string bname = filterContext.ActionDescriptor.ActionName;//方法名称
    string aname = filterContext.HttpContext.Request.HttpMethod;//请求方式
    book.MSysLogs.Add(new MSysLog()
    {
    logtime = DateTime.Now,
    content = $"通过了{aname}方式调用了{cname}控制器{bname}方法"
    });
    book.SaveChanges();
    }
    }

    写这篇文章时候入的坑:我的表中没有主键,所以创建EF或者更新EF的时候没有这个表.... 
  • 相关阅读:
    HDU5213(容斥定理+莫队算法)
    HDU4467:Graph(点的度数分块)
    BZOJ3834:Solar Panels (分块)
    BZOJ2217:Lollipop
    “玲珑杯”线上赛 Round #17 河南专场 B:震惊,99%+的中国人都会算错的问题(容斥计算)
    Linux环境及基础命令(一)
    阿里前CEO卫哲:马云好玩,人工智能泡沫巨大,新零售重在社区
    配置JDK和Tomcat环境变量
    批处理_批量替换不同语句
    批处理命令_提取当前目录下所有文件名称
  • 原文地址:https://www.cnblogs.com/ZaraNet/p/9519328.html
Copyright © 2011-2022 走看看