.net mvc登陆身份判断

在初初开始要使用asp.net mvc开发一个所谓的网站(或管理系统)的时候,就有这么一个功能需求,就是在做登陆功能的时候,要如何避免使用者会绕过登陆界面直接定位到某个控制器下的某个方法去访问网站(如a.com/Account/InfoDetail),这个时候一般的思路就是在那些需要登陆者身份的页面进行session判断

在ASP.NET MVC Framework中支持四种不同类型的Filter与其一般的执行顺序:

Authorization filters – 实现IAuthorizationFilter接口的属性(验证Filter)——>Action filters – 实现IActionFilter接口的属性——>Result filters – 实现IResultFilter接口的属性——>Exception filters – 实现IExceptionFilter接口的属性(异常Filter);当然你也可以根据需要通过Order属性设定过滤器执行的顺序。

在MVC框架调用acion之前,它会先判断有没有实现上面的接口的特性,如果有,则在请求管道的适当的点调用特性中定义的方法。

那么,我们一般的做法就是将判断登陆的方法实现第一个Filter接口,即实现IAuthorizationFilter接口,不说了,直接copy一下代码

public class AuthenAdminAttribute : FilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
            //这个方法是在Action执行之前调用
        var user = filterContext.HttpContext.Session["AdminUser"];
        if (user == null)
        {
            //filterContext.HttpContext.Response.Redirect("/Account/Logon");
            var Url = new UrlHelper(filterContext.RequestContext);
            var url = Url.Action("Logon", "Account", new { area=""});
            filterContext.Result = new RedirectResult(url);
        }
    }
    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        //这个方法是在Action执行之后调用
    }
}

注意:上面OnAuthentication是在最开始被调用的,也在ActionFilter方法之前。而OnAuthenticationChallenge方法是在Action执行之后,返回视图之前被调用。所以要把登录验证写在方法OnAuthentication中。而且在里面我们用到了设置filterContext.Result = new RedirectResult(url);而不是跳转的形式。MVC在执行Filter时,如果我们手动用一个ActionResult对象指定了其Context对象的Result属性的值,那么这个这个ActionResult将作为这个请求的结果输出,并且在这次请求管道中剩下的步骤将不再继续执行。反之如果没有设置filterContext.Result的值,它会继续执行接下来的步骤,甚至是Action方法,就算我们设置了跳转。

public class AccountController : Controller
{
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(string username,string password)
        {
            if (Username == "admin" && Password == "admin")
            {
                Session["LoginUser"] = username;
                return RedirectToAction("Index",
                                        "Order", new { area = "Admin" });
            }
            else
                ViewBag.Error = "用户名或密码不正确!";
            return View();
        }
       
        public ActionResult LogOff()
        {
            if (Session["AdminUser"] != null)
            {
                Session["AdminUser"] = null;
            }
            return RedirectToAction("Login");
        }
 }

注意:大概的代码如上,这里登录成功之后的存Session的key一定要和上面第一步的AuthenAdminAttribute用到的key一致。

最后一步就是根据需要进行登陆判断,在需要的Controller或者Action上添加属性[AuthenAdmin]。

 

参考:

http://www.lanhusoft.com/Article/73.html

http://www.cnblogs.com/willick/p/3331520.html

http://www.cnblogs.com/jyan/archive/2012/07/24/2606547.html

posted @ 2017-05-19 11:54  大寳  阅读(331)  评论(0编辑  收藏  举报