当前位置: 代码迷 >> VC/MFC >> MVC中验证登录跟权限
  详细解决方案

MVC中验证登录跟权限

热度:163   发布时间:2016-05-02 03:50:54.0
MVC中验证登录和权限

用mvc做后台管理系统,必然会要做登录和权限判断。这里是用mvc的ActionFilterAttribute特性。

具体如下:

声明一个CheckUser类,继承ActionFilterAttribute类

public class CheckUserFilter : ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    base.OnActionExecuting(filterContext);
    if (filterContext.HttpContext.Request.Cookies["backUser"] == null)
    {
      filterContext.HttpContext.Response.Redirect("~/Home/Login");//为登录跳转到登录页面
    }
    else
    {
      string controllerName = filterContext.RouteData.Values["controller"].ToString();
      BackLogin blogin = new BackLogin();
      bool l = blogin.IsLogin();//再次验证cookies中的信息是否正确,防止伪造
      if (l == false)
      {
        filterContext.HttpContext.Response.Redirect("~/Home/Login");
      }
      else
      {
        bool b = blogin.IsHavaRights(controllerName);//验证权限
        if (b == false)
        {
          filterContext.HttpContext.Response.Redirect("~/Home/NoRight");
        }
      }
    }
  }

}

接下来就简单了,只要在要验证的action上添加验证即可

[CheckUser]public ActionResult Index(){       return View();  }

如果没有登录,或者没有权限就会跳转到相应的页面了。

当然mvc中还有其他的验证特性如AuthorizeAttribute类。具体使用方法,网上一大堆。

 

转载请注明出处。

  相关解决方案