过滤器+用session验证是否登陆过

过滤器:

public class MyActionFilter : ActionFilterAttribute//继承ActionFilterAttribute类
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //用session验证是否登陆过
            if(filterContext.HttpContext.Session["visitor_name"] == null)
            {
                //未登录则跳转到登录页面,并拖过url?传递状态码?Login_state=false用于前端验证并友好提示
                filterContext.HttpContext.Response.Redirect("/Login_/Index?Login_state=false",true);
            }
        }
    }

Login_Controller.cs:

        public ActionResult Login(string name, string pwd)//传进来的字符串实际没用上
        {
            var get_name = Request["name"];
            var get_pwd = Request["pwd"];
            JJQPractice visitor = JJQPractice.SingleOrDefault(new { name = get_name });//得到对应输入的账号的集
            if (visitor != null)//验证输入的账号是否存在
            {
                if (visitor.pwd == get_pwd)//验证密码是否正确
                {
                    Session["visitor_name"] = get_name;//在session中写入name用于判断登录状态
                    return RedirectToAction("Index", "Select_");//密码正确后跳转到查询视图
                }
                else
                {
                    Response.Write("登录失败!密码错误.");
                    return View("Index");
                }
            }
            else
            {
                Response.Write("登录失败,用户名不存在.");
                return View("Index");
            }
        }

你可能感兴趣的:(过滤器+用session验证是否登陆过)