zoukankan      html  css  js  c++  java
  • MVC中的action验证登录(ActionFilterAttribute)

    方法一 : 1. 创建一个全局action过滤器  (在appstart  的 filterconfig中注册   filters.Add(new LoginFilterAttribute());)

                     这样就每个Action都会执行此过滤器,而不必每个Controller顶部都加上标签。                

        public class FilterConfig
        {
            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new HandleErrorAttribute());
                //注册全局过滤器
                filters.Add(new LoginFilterAttribute() { Message = "全局" });
            }
        }

               2不需要登录的contoller或者action  则在该类或者action上添加该过滤器特性 (isNeed=false)                 

    {
           [LoginFilterAttribute(isNeed = false)]
           public class UserController : Controller
           {
                   public ActionResult Login()
                   {
                        return View();
                   }
           }
    }

     方法二: 1. 创建一个filter 不在全局注册

                 2. 创建 一个baseControler ,然后再basecontroller上边添加该filter特性

                 3. 需要登录的则继承该basecontroller,不需要登录的则不继承该basecontroller

                  补充:若是不想建baseControler ,可以直接在Controller控制器上或者Action方法上加自定义的过滤器

       注意: 1. OnActionExecuting 中   base.OnActionExecuting(filterContext);

                     如果当前项目有多个filter则加上 base.OnActionExecuting(filterContext); 

                     不添加则不会执行其他的filter 

                 2. filterContext.Result = new RedirectResult("/User/login");

                  在filter里边页面跳转用  filterContext.Result = new RedirectResult("/User/login");

                  如果用 filterContext.HttpContext.Response.Redirect("/User/login");  则在跳转后还会继续执行  后边的action  eg: home/index    跳转user/login  后,还会接着执行index/action  里边的方法

                  在Filter中用Response.Redirect,虽然URL是跳转了,但是之后的Filter和Action还是会执行,不仅浪费资源,还会产生一些不必要的错误 

  • 相关阅读:
    MySQL 初识别语句,数据库、表、行的增删改查
    mysql如何从全备文件中恢复单个库或者单个表
    Shell 同步时间脚本
    app手机端连接tomcat电脑端服务器
    大于号转义符>---小于号转义符<
    轻松实现页面提交中
    重复提交问题(一)
    json
    ExtJs 6.0+快速入门,ext-bootstrap.js文件的分析,各版本API下载(一)
    ExtJS 6 如何引入Dashboard模版
  • 原文地址:https://www.cnblogs.com/li150dan/p/9957971.html
Copyright © 2011-2022 走看看