原文地址:.net mvc 控制器拦截器 登录控制
在实际项目开发中,很多时候,需要判断用户是否已经登录,对于一些需要做出数据权限控制的系统来说,获取到当前用户的登录信息,这更是有必要的。如果用户没有登录,则需要跳转到登录界面进行登录操作。
本文着重介绍.net mvc 在拦截器中实现登录验证和控制。
第一步:
新建一个类,继承自 ActionFilterAttribute 类,重写里面的OnActionExecuting方法,意思就是只要执行指定的控制器类,都会先执行这个方法。
public class AuthAttribute : ActionFilterAttribute
{
#region 是否登录
public bool IsLogin
{
get;
set;
}
#endregion
/// <summary>
/// 验证登录(action执行前会先执行这里)
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (IsLogin == true)
{
//如果不存在身份信息
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
ContentResult Content = new ContentResult();
Content.Content = string.Format("<script type='text/javascript'>alert('请先登录!');window.location.href='{0}';</script>", "/Tuser/Login");
filterContext.Result = Content;
}
}
}
}
第二步:
在你需要拦截的控制器头上 添加
[AuthAttribute(IsLogin = true)]
这里的true 表示,该方法需要先判断用户是否登录,如果不需要先验证登录信息的话,则可以不写也可以islogin为false
[AuthAttribute(IsLogin = true)]
[HttpGet]
public ActionResult UppassForm(string code)
{
...
}
这样只要调用了这个UppassForm控制器,则会先判断是否登录,未登录的话则会提示请登录,效果如图
至于用户登录以后,你可以把信息写入cookie中,上面的拦截器里的判断方法,你可以根据实际需求从cookie里取值,或者就直接采用这种写法均可以
string UserData = JsonConvert.SerializeObject(resultDt);//序列化用户实体
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, "userInfo", DateTime.Now, DateTime.Now.AddHours(12), false, UserData);
HttpCookie Cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(Ticket));//加密身份信息,保存至Cookie
Response.Cookies.Add(Cookie);
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
.NET C# JAVA 基础交流群 1095936339 欢迎入群 交流!