如下面的代码我们建一个CustomAuthorizeAttribute类 [cce_cs]using System;us
MVC框架的开发网站的利器,MVC框架也开始越来越风行了。对付.NET ,微软也颁布了MVC框架,做网站凡是要涉及到用户的权限打点,对付.NET MVC 框架的用户权限打点又应该怎样设置呢?下面通过示例讲解一下怎样实现.NET MVC 用户权限打点。
检察微软MSDN库我们知道,ASP.NET MVC权限控制都是通过实现AuthorizeAttribute类的OnAuthorization要领。因此我们需要将一个类来担任AuthorizeAttribute类,并实现OnAuthorization要领。如下面的代码我们建一个CustomAuthorizeAttribute类
[cce_cs] using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; /// /// Summary description for CustomAuthorizeAttribute /// public class CustomAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { bool isAuthenticated=HttpContext.Current.Session["User"]==null?false:true; if (!isAuthenticated) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "account", action = "login", returnUrl = filterContext.HttpContext.Request.Url, returnMessage = "您无权检察." })); return; } base.OnAuthorization(filterContext); } } [/cce_cs]上面的代码假设用户登录的标识是存储Session中,key为USer,这样通过判断是否有这个标识作为是否登录的判断,固然这里的用户登录标识只是示例,你完全可以按照本身的要领实现isAuthenticated的登录判断。如果没有登录,上面的代码会重定向到登录页面。
因此我们此刻有了CustomAuthorizeAttribute标签,只需要给我们的Action要领打上[CustomAuthorizeAttribute] 标签就可以了,如下面的代码:
[cce_cs] using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace SampleMVCWebsite.Controllers { public class HomeController : Controller { // // GET: /Home/ [CustomAuthorize] public ActionResult Index() { return View(); } } } [/cce_cs]这样上面的代码就会有这样的效果:当访谒 HomeController 的 Index 要领的时候就会首先执行 CustomAuthorizeAttribute 类中的
OnAuthorization判断是否登录,,如果没有就跳到登录页面。
像上面这种方法是对照粗粒度的解决方案,由于是已经将界说好权限的固定代码带对应的Action上,所以无法实现用户自界说权限控制。下一次教程讲解.NET MVC基于角色的权限控制系统。
ASP.NET MVC 用户权限-1
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/29950.html