mvc 验证登录

很多时候,我们需要多个页面验证用户是否登录

有2中方法。

一种是继承 Attrbuite属性,添加验证,这个可以网上搜索。

我一般使用下面的方式

创建BaseWebController继承Controller。

然后实现OnActionExcuting方法,这样所有继承BaseWebController的Controller中,访问Action时,都会先跑到这里,如果没有登录,就会跳转到Login页面

public class BaseWebController : Controller
    {

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //user为空,并且不是登录页面,则跳转到登录页面。
            if ((filterContext.HttpContext.Session["User"] == null || CurrentUser.id == 0) 
                && (controllerName != "Login" && actionName != "Login"))
            {
                filterContext.HttpContext.Response.Redirect("/Login/Login");
            }

            base.OnActionExecuting(filterContext);
        }

    }

PS:测试一下,多个用户同时登陆,session是否会被覆盖。

我这里没这个问题。

原文地址:https://www.cnblogs.com/hanjun0612/p/9779902.html