我AOP的设计理念在软件开发中的应用愈来愈普遍,这不是一个高大上的东西,而是每一个程序员都应该熟知的一个东西。由于它方便的就是咱们程序员。使用AOP,咱们能够专一于逻辑代码的编写,将那些系统功能统一交给AOP框架去管理,在运行时自动耦合起来。
当咱们访问URL页面时,好比A能够浏览全部页面。B只能够浏览一部分页面,若是没有一个统一的权限控制,只要URL地址正确,你们均可以访问。这样就没权限控制可言了。因此在访问页面中以前,咱们先去自动执行我写的权限判断。
具体知道我要干什么了,那么怎么实现呢?
我自定义了一个filter——AuthAttribute。
一、假如我要执行以下这个Controller下的Action。这个Controller和Action都是你们本身编写的,这里只是个实例。
php
namespace ITOO.BasicPlaceClient.Controllers java
{ 程序员
//控制器类,继承了Controllers web
public class MyController : Controller 缓存
{ 框架
public ActionResult Index() ide
{ 学习
return View(); ui
} spa
}
}
复制代码
二、在执行以前,先进行权限判断,执行我写的这个自定义的filter。在这里,咱们会取出你简要访问的Controller和Action,在缓存了取出你所拥有的访问权限。在这里判断你是否有访问该Controller里的Action的权限。没有权限,直接给出友好提示,你没有权限。嘿嘿,还算是友好吧。可是你要是拥有权限,他会继续执行你要访问的Action,将你想要见到的页面呈现给您。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ITOO.Library.Core.Memcache;
using System.Collections;
namespace ITOO.BasicPlaceClient.Controllers.Attribute
{
///
/// ActionFilterAttribute是Action过滤类,该属于会在执行一个action以前先执行.而ActionFilterAttribute是 MVC的一个专门处理action过滤的类.基于这个原理作的一个权限限制。
///
public class AuthAttribute : ActionFilterAttribute
{
///
/// 在执行操做方法以前由 ASP.NET MVC 框架调用
///
///
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
////获取 controllerName 名称
var controllerName = filterContext.RouteData.Values["Controller"].ToString();
///获取你将要执行的Action的域名
var actionName = HttpContext.Current.Request.RequestContext.RouteData.Values["Action"].ToString();
Guid selfGuid1 = Guid.NewGuid();//申请了一个模拟的GUID
Guid selfGuid2 = Guid.NewGuid();//申请了一个模拟的GUID
MemcacheHelper.Add(selfGuid1.ToString(), "QueryBed", DateTime.Now.AddMinutes(20));
//Controller存入缓存
MemcacheHelper.Add(selfGuid2.ToString(), "Index", DateTime.Now.AddMinutes(20));
//Action存入缓存
//建立一个List集合
List guids1 = new List();
//将缓存里取出的key值存放到List里
guids1.Add(selfGuid1.ToString());
guids1.Add(selfGuid2.ToString());
//建立数据字典getkey对象
IDictionary getkey = new Dictionary();
//获取一组缓存
getkey = MemcacheHelper.Get(guids1);
//验证权限,先验证Controller
foreach (KeyValuePair kvp in getkey)
{
//若是有将要访问的Controller的权限
if (kvp.Value.ToString() == controllerName)
//若是有将要访问的Acting的权限
foreach (KeyValuePair kvp1 in getkey)
if (kvp1.Value.ToString() == actionName)
{
//所有经过,则存在访问将要访问的Controller下的Action
return;
}
}
//没有权限,验证不经过
ContentResult Content = new ContentResult();
Content.Content = "
//执行结果为权限不经过
filterContext.Result = Content;
}
}
}
复制代码
这是权限判断的代码。在使用它以前,咱们要在Global里面的RegisterGlobalFilters进行注册。不然在方法执行以前是不会执行这段代码的。
三、注册:
filters.Add(new AuthAttribute());
复制代码
这样,就实现了一个简单的权限控制。技术浅薄,就写成这样了,有什么不对的你们互相交流。
更多java学习 web框架学习 http://techfoxbbs.com