MVC用filter的简单应用[转]
MVC用filter应用
Admin
2012年7月26日
MVC用filter做权限过滤:查看原文
1:创建filter类;类须要持续一个接口,并且重写4个办法;如下:
1 namespace MvcApplication1.Code 2 { 3 public class paramFilter:System.Web.Mvc.ActionFilterAttribute 4 { 5 public override void OnActionuted(System.Web.Mvc.ActionutedContext filterContext) 6 { 7 base.OnActionuted(filterContext); 8 } 9 10 11 public override void OnActionuting(System.Web.Mvc.ActionutingContext filterContext) 12 { 13 if(filterContext.HttpContext.Request.QueryString["k"]=="go") 14 { 15 string retUrl = filterContext.RouteData.GetRequiredString("controller") + "/" + filterContext.RouteData.GetRequiredString("action"); 16 filterContext.HttpContext.Response.Redirect("http://" + filterContext.HttpContext.Request.Url.Host + ":" + filterContext.HttpContext.Request.Url.Port.ToString() + "/" + retUrl); 17 } 18 } 19 20 21 public override void OnResultuted(System.Web.Mvc.ResultutedContext filterContext) 22 { 23 base.OnResultuted(filterContext); 24 } 25 26 27 public override void OnResultuting(System.Web.Mvc.ResultutingContext filterContext) 28 { 29 base.OnResultuting(filterContext); 30 } 31 } 32 }
重视:此中 filterContext对象是 从页面传过来的。
获取页面controller值的办法是 filterContext.RouteData.GetRequiredString("controller")
获取页面action值的办法是: filterContext.RouteData.GetRequiredString("action")
转到其他页面的办法是: filterContext.HttpContext.Response.Redirect()I
ip: filterContext.HttpContext.Request.Url.Host
端口:filterContext.HttpContext.Request.Url.Port.ToString()
2:在须要过滤的controller上加上一句代码即可:
1 [Code.paramFilter] 2 public ActionResult Index() 3 { 4 5 return View(); 6 }
本文来自博客园,作者:清玄-2012,转载请注明原文链接:https://www.cnblogs.com/happy-tears/archive/2012/07/27/2612069.html