• mvc5权限管理(简单登录):ActionFilterAttribute


    效果图:

    1.控制器

     public ActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public ActionResult Index(User user)
            {
                if( LoginBLL.CheckLogin(ref user)) { 
                    MyCookie.Write(user);
                return Content("loging is ok <a href='/jq/List'>查看</a>");
                }
                else
                {
                    
                    return Content("login is error:");
                }
            }
    
            public ActionResult List() {
                User user = MyCookie.ReadCurCookie();
                string con =  "card = " + user.card + " pwd = " + user.pwd + " lv =" + user.lv +"<p/>" ;
                con += "<a href='write'>写</a><p/>";
                con += "<a href='read'>读</a><p/>";
                return Content(con);
            }
    
            [MyValidate(PowType = 1)] //权限管理 权限为1
            public ActionResult read() {
                return Content("you can read");
            }
            [MyValidate(PowType = 2)] //权限管理 权限为2
            public ActionResult write() {
                return Content("you can write");
            }
    
            public ActionResult error()
            {
                return Content("权限不够哦");
            }
    View Code

    这个里面的模型类是:

        public class User
        {
            public string card { get; set; }
            public string pwd { get; set; }
            public int lv { get; set; }
        }
    View Code

      

    2.封装类 

      设置权限验证的类:

        public class MyValidate : ActionFilterAttribute
        {
            public string Power;
            public int PowType;
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                try
                {
                    // user is cooke infor
                    User mod = MyCookie.ReadCurCookie();
                    // check login status
                    if (!LoginBLL.CheckLogin(ref mod))
                    {
                        filterContext.Result = new RedirectResult("/JQ/index");
                    }
                    // Pow type is control on [MyValidate(PowType = ?)] set values             
                    if ( mod.lv != PowType)
                    {
                        filterContext.Result = new RedirectResult("/jq/error");
                        //this return route(
                        //new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "Home", action = "Default" }));
                    }
                }
                catch
                {
                    filterContext.Result = new RedirectResult("/JQ/Login");
                }
            }
    
            //当方法执行完毕
            public override void OnActionExecuted(ActionExecutedContext filterContext)
            {
                base.OnActionExecuted(filterContext);
            }
        }
    View Code 

      读写cookie

            public class MyCookie
            {
                public static void Write(User user)
                {
                    FormsAuthentication.SetAuthCookie(user.card, true, FormsAuthentication.FormsCookiePath);
                    //把用户对象保存在票据里
                    FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, user.card, DateTime.Now, DateTime.Now.AddTicks(FormsAuthentication.Timeout.Ticks), false, MyJosnHelper.ToJson(user));
                //MyJosnHelper.ToJson(user) 存储在票据的 UserData 处,这个地方怎么操作由你决定
                //加密票据
                string hashTicket = FormsAuthentication.Encrypt(Ticket);
                    HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
                    System.Web.HttpContext.Current.Response.Cookies.Add(userCookie);
                }
    
                public static User ReadCurCookie()
                {
                    try
                    {
                        var cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; //的到Cookie
                        if (cookie == null)
                            return null;
                        var ticket = FormsAuthentication.Decrypt(cookie.Value); //解密票据
                        string str = ticket.UserData; 
                        return MyJosnHelper.JsonDeserialize<User>(str);
                    }
                    catch
                    {
                        return null;
                    }
                }
    
                public static void ReMoveCookie()
                {
                    FormsAuthentication.SignOut();
                }
            }
    View Code

      模型json互转

        public class MyJosnHelper
        {
            public static T JsonDeserialize<T>(string jsonString) 
            {
                return JsonConvert.DeserializeObject<T>(jsonString);
            }
    
            public static string ToJson(object obj)
            {
                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                return JsonConvert.SerializeObject(obj);
            }
    
        }
    View Code

    2016.5.12  使用部分视图显示登陆效果 

    @using Microsoft.AspNet.Identity
    @using ssm.Models
    @using SSM.comm
    
    @if ( MyCookie.Read() != null )
    {
        <ul class="nav navbar-nav navbar-right">
            <li>
                @Html.ActionLink("你好," +  MyCookie.Read().Adm_Name + "!", "Infor", "grzx", routeValues: null, htmlAttributes: new { title = "Manage" })
            </li>
            <li><a href="/home/out">注销</a></li>
        </ul>
    }
    else
    {
        <ul class="nav navbar-nav navbar-right">
            <li>@Html.ActionLink("登录", "Login", "Home", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
        </ul>
    }
    View Code

    扩展文档:

    http://www.cnblogs.com/zxjyuan/archive/2009/08/21/1551196.html   FormsAuthenticationTicket对象

    代码包:效果在控制器 jq里面

    http://pan.baidu.com/s/1kUx7I31

  • 相关阅读:
    squid代理缓存服务
    部署网络存储ISCSI
    电子邮局系统
    使用DHCP动态管理主机地址
    vsftp -samba-autofs
    python初学 | 循环for while
    python初学 | 条件语句if
    python初学 | set
    python初学 | 字典dictionary
    python初学 | 元组tuple
  • 原文地址:https://www.cnblogs.com/0to9/p/5291213.html
Copyright © 2020-2023  润新知