MVC用filter使用
MVC用filter做权限过滤:
1:创建filter类;类需要继承一个接口,并且重写4个方法;如下:
namespace MvcApplication1.Code
{
public class paramFilter:System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuted(System.Web.Mvc.ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
}
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
{
if(filterContext.HttpContext.Request.QueryString["k"]=="go")
{
string retUrl = filterContext.RouteData.GetRequiredString("controller") + "/" + filterContext.RouteData.GetRequiredString("action");
filterContext.HttpContext.Response.Redirect("http://" + filterContext.HttpContext.Request.Url.Host + ":" + filterContext.HttpContext.Request.Url.Port.ToString() + "/" + retUrl);
}
}
public override void OnResultExecuted(System.Web.Mvc.ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
}
public override void OnResultExecuting(System.Web.Mvc.ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
}
}
}
注意:其中 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上加上一句代码即可:
[Code.paramFilter]
public ActionResult Index()
{
return View();
}