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],就可以实现登录验证了,哎。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值