码迷,mamicode.com
首页 > Web开发 > 详细

MVC Filter登录验证

时间:2019-11-24 00:04:48      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:NPU   登录   contex   没有   tab   turn   highlight   str   ret   

Login Controller

        public ActionResult Index()
        {
            //return Content("hello index!");
            return View();
        
        }
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(string username, string password)
        { 
            if(username=="111"&&password=="111")
            {
                Session["UUU"] = "111";
                return RedirectToAction("Index");
            }
            else
            {
                return Content("登录失败!");
            }
        
        }

Index View

<h2>Index</h2>
<text>主页运行成功</text>

Login View

<form action="/Login/Login" method="post">
    用户名<input type="text" name="username" value="" />
    密码<input type="text" name="password" value="" />
    <input type="submit" name="name" value="提交" />

</form>

CheckLoginFilter

using System.Web.Mvc;//别引用错了


 public class CheckLoginFilter:IAuthorizationFilter  
    {


        public void OnAuthorization(AuthorizationContext filterContext)
        {
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string actionName = filterContext.ActionDescriptor.ActionName;
            if (controllerName == "Login" && actionName == "Login")
            {
                
            }
            else
            {
                if (filterContext.HttpContext.Session["UUU"] == null)
                {
                    //ContentResult contexts = new ContentResult();
                    //contexts.Content = ("没有登录");
                    //filterContext.Result=contexts;
                    filterContext.HttpContext.Response.Redirect("/Login/Login");
                     
                    
                }
            }
        }
    }

Global

 RouteConfig.RegisterRoutes(RouteTable.Routes);
 GlobalFilters.Filters.Add(new CheckLoginFilter() );//添加filter

  

MVC Filter登录验证

标签:NPU   登录   contex   没有   tab   turn   highlight   str   ret   

原文地址:https://www.cnblogs.com/lierjie/p/11920529.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!