MVC中方便的[Authorize],加上这特性,就可以加上登录验证

之前不知道有这个特性,还翻查代码,找各种方法

 

实现访问某些控制器,需要登录

 

方法如下:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using Microsoft.AspNet.Identity;

namespace Star.BackPortal.Controllers {

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false)]

    public sealed class CheckLogin : Attribute {

        public bool IsNeedLogin = false;

        public CheckLogin(bool isNeed) {

            this.IsNeedLogin = isNeed;

        }

    }

    public class ParentController : Controller {

        protected override void OnActionExecuting(ActionExecutingContext filterContext) {

            base.OnActionExecuting(filterContext);

            bool result = false;

            //controller上是否有特性CheckLogin,以及特性的IsNeedLogin值

            var controllerAttrs = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(CheckLogin), false);

            if (controllerAttrs.Count() > 0) {

                var conAttr = controllerAttrs[0] as CheckLogin;

                if (conAttr != null) {

                    if (conAttr.IsNeedLogin)

                        result = true;

                    else

                        result = false;

                }

            }

            //action上是否有特性CheckLogin,以及特性的IsNeedLogin值

            var actionAttrs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(CheckLogin), false);

            if (actionAttrs.Count() > 0) {

                var attr = actionAttrs[0] as CheckLogin;

                if (attr != null) {

                    if (attr.IsNeedLogin)

                        result = true;

                    else

                        result = false;

                }

            }

            if (!IsLogin() && result) {

                //如果没有登录,则跳至登陆页

                filterContext.Result = Redirect("/Account/Login");

            }

        }

        protected bool IsLogin()

        {

            string userId = User.Identity.GetUserId();

            if (userId != null)

                return true;

            return false;

        }

    }

}

 

后来才发些,微软本身就做了。只要在控制器加上[Authorize],就可以实现登录验证了,哎。。。

你可能感兴趣的:(技术)