• ASP.NET MVC下判断用户登录和授权状态方法


    在我们日常开发的绝大多数系统中,都涉及到管理用户的登录和授权问题。登录功能(Authentication),针对于所有用户都开放;而授权(Authorization),则对于某种用户角色才开放。

    在asp.net mvc中,微软虽然已经帮助开发者构建了ASP.NET Identity这样强大的验证授权框架,但是如果想定制更多的逻辑功能的话,还得自己动动手。

    根据日常的开发经验,我总结了大概下面2种方法:

    1、继承Controller:

    1.1 在我最早的时候,比较单纯,也许是从WebForm那里学来的招式,我并没有细读Controller里的所有方法,所以在派生类里自己添加了验证方法,然后在每个Action方法里调用。此方法现在看来有些蛋疼...

    派生类如下:

    public class AuthenticationControllor : Controller
    {
        public bool Validate()
        {
            if (Session["username"] == null)
                return false;
            else
                return true;
        }
    
        public ActionResult RedirectLogin(bool redirect = true)
        {
            if (redirect)
                return RedirectToAction("Login", "Home", new { from = Request.Url.ToString() });
            else
                return RedirectToAction("Login", "Home");
        }
    }

    使用类如下:

    public class HomeController : AuthenticationControllor
    {
        public ActionResult Index()
        {
            if (!Validate())
                return RedirectLogin();
     
            return View();
        }
    }

    1.2 后来学习了很多人的代码后,发现在Controller里有一个OnActionExecuting方法,此方法是在Action之前执行的,非常方便。

    派生类如下:

    public class AuthenticationControllor : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Session["username"] == null)
                filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary { { "from", Request.Url.ToString() } });
                
            base.OnActionExecuting(filterContext);
        }
    }

    使用类如下:

    // 不需要多写任何逻辑代码就能判断是否登录并跳转
    public class HomeController : AuthenticationControllor
    {
        public ActionResult Index()
        { 
            return View();
        }
    }

    2. 继承ActionFilterAttribute:

    由于继承Controller方法不太适合一个Controller下的有些Action需要登录有些Action不需要登录的场景,所以针对每个Action写一个统一的特性会更好一些。

    ActionFilterAttribute里也有OnActionExecuting方法,跟Controller一样, 同是抽象实现了IActionFilter接口。

    派生类如下:

    // 登录认证特性
    public class AuthenticationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Session["username"] == null)
                filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary { { "from", Request.Url.ToString() } });
                
            base.OnActionExecuting(filterContext);
        }
    }

    使用方法如下:

    public class HomeController : Controller 
    { 
        [Authentication] 
        public ActionResult Index()
        {
            return View();
        }
    }

    如果你想针对整个MVC项目的所有Action都使用此过滤器,步骤如下:

    a. 确保Global.asax.cs的Application_Start方法中包含如下红色行

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
    
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }

    b. 在FilterConfig.cs文件中注册相应的特性过滤器:

    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new AuthenticationAttribute());
        }
    }

    推荐大家使用第2种过滤器的方法实现认证和授权。

  • 相关阅读:
    [VB]VB操作Execl大全
    架构实战软件架构设计的过程
    “如何管理软件企业”之软件行业的三类主要盈利模式
    交互设计指南
    编写高质量代码Web前端开发修炼之道
    《裂变——看得见的未来》新书首发式暨读者联欢会
    只懂执行其他人测试想法的人,不能算真正的测试人
    敏捷联盟Gordon Pask奖获得者讲“测试驱动开发”(TDD)
    《裂变》作者爆料:欺世盗名者绝非唐骏一人
    《团队之美》的那些作者们
  • 原文地址:https://www.cnblogs.com/stozen/p/4977691.html
Copyright © 2020-2023  润新知