zoukankan      html  css  js  c++  java
  • MVC项目开发中那些用到的知识点(登录权限认证)

         话说从开始接触MVC到现在也有一段时间了,记得好像是从2012年8月初开始做项目的。就记录一下自己所用到的且认为重要的知识点吧。

    首先做的便是一个登录,那么就用到了登录权限认证:

        public class UserAuthentication : AuthorizeAttribute
        {
            public UserToUrlEnum UserToUrlEnum { get; set; }
    
            public UserAuthentication()
            {
                this.UserToUrlEnum = UserToUrlEnum.Login;
            }
            /// <summary>
            /// 视图响应前执行验证,查看当前用户是否有效
            /// </summary>
            public override void OnAuthorization(AuthorizationContext filterContext)
            {
                if (filterContext.HttpContext.Session.IsNewSession && string.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
                {
                    switch (this.UserToUrlEnum)
                    {
                        case UserToUrlEnum.Login:
                            {
                                HttpContext.Current.Response.Redirect("~/Account/Login"
                                    , true);
                            }
                            break;
                    }
                }
            }
        }

    此类首先有继承AuthorizeAttribute,重载OnAuthorization此方法,以便与在每次触发Action之前调用此方法,检验是否已经登录以及用户是否已经过期。如果过期或者没登录,那么就会自动返回到登录页面,要求登录。

    刚刚说到了每次触发Action之前调用OnAuthorization此方法,那么如何触发呢:

            [UserAuthentication]
            public ActionResult RoleManagerPage()
            {
                return View();
            }

    只需要在要检验的Action前加上该属性标识即可。也可以加到整个控制器上面。代码如下

        [UserAuthentication]
        public class SystemManagerController : Controller

    那么此控制器下的每个Action在执行的时候都会做用户登录权限的认证。

    用户如果没有登录,而是通过Url直接访问,那么就会跳转到登录页面,要求登录;或者用户长时间无操作,那么之前登录的用户将会过期,同样会跳转到登录页面。

    当然还要在配置文件System.Web节点下添加  

      <authentication mode="Forms">       <forms loginUrl="~/Account/Login" protection="All" timeout="30" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="~/Home/Index" cookieless="UseDeviceProfile" enableCrossAppRedirects="false"/>     </authentication>

  • 相关阅读:
    响应式css样式
    组件 computed 与 vuex 中 getters 的使用,及 mapGetters 的使用,对象上追加属性,合并对象
    nginx 错误集锦
    动态的添加路由
    NProgress的使用 及 路由 token 定向的使用
    token的解码及 判断值不为空的方法
    nginx 的使用
    IT公司100题-tencent-打印所有高度为2的路径
    测试
    Objective-C 与 C++ 的异同
  • 原文地址:https://www.cnblogs.com/aehyok/p/2764134.html
Copyright © 2011-2022 走看看