IAuthorizationFilter学习笔记(权限控制)以及非全局的filter

第一步:新建类CheckLoginFilter实现接口IAuthorizationFilter。请注意接口位于命名空间using System.Web.Mvc;

public void OnAuthorization(AuthorizationContext filterContext)
{
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = filterContext.ActionDescriptor.ActionName;
if(controllerName=="Login"&&(actionName.ToUpper()=="index".ToUpper() || actionName.ToUpper() == "login".ToUpper()))
{

}
else
{
//检查登陆状态
if (filterContext.HttpContext.Session["username"] == null)
{
ContentResult con = new ContentResult();
con.Content = "没有登陆";
filterContext.Result = con;
}
}
}

第二步;将过滤器添加到Global.asax中

GlobalFilters.Filters.Add(new CheckLoginFilter());

如上所示的代码 假如没有检测到session,即用没有登录,此时返回字符串。同理也可实现当用户没有登陆时跳转到登陆页面。代码如下所示:

//ContentResult con = new ContentResult();
//con.Content = "没有登陆";
RedirectResult red = new RedirectResult("/login/index");
filterContext.Result = red;

其实就是使用类RedirectResult 。

那么此时会存在一个问题   如果我想让某一部分action  或者说某一部分controller实现过滤器 另外的一些不实现这些过滤器 此时应该怎么做?参考微软的特性attribute  这个过滤器也有类似的用法

首先,让实现的类继承自FileterAttribute类  然后实现具体的filter接口  此时不需药操作golbal.asax来添加了 而是像特性一样写在相应的action 或者controller前面。

具体用法如下:

public class TestAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = filterContext.ActionDescriptor.ActionName;

//检查登陆状态
if (filterContext.HttpContext.Session["username"] == null)
{
//ContentResult con = new ContentResult();
//con.Content = "没有登陆";
RedirectResult red = new RedirectResult("/login/index");
filterContext.Result = red;
}
}
}

现在有两个action Index和zhuanzhang  其中index标明了attribute  那么就只有在访问index时才会过滤   zhuanzhang的action不会有反应

[Test]
public ActionResult Index()
{
return Content("index页面的展示"+Session["username"]);
}

public ActionResult zhuanzhang()
{
return Content("开始转账" + Session["username"]);
}

如果将特性标记到controller上,那么都会去走过滤的方法

原文地址:https://www.cnblogs.com/yagamilight/p/12217912.html