mvc 4 ActionFilterAttribute 特性,进行权限验证

权限验证:

 /// <summary>
/// 管理员身份验证
/// </summary>
public class BasicAuthenticationAttribute : ActionFilterAttribute
{
/// <summary>
/// 管理员信息
/// </summary>
public Admin Model { get; set; }
/// <summary>
/// 构造函数,进行获取管理员信息
/// </summary>
public BasicAuthenticationAttribute()
{
string admininfo = CookieHelper.GetCookie("AdminInfo"); if (!string.IsNullOrEmpty(admininfo))
{
Model = MemcachedHelper.Get<Admin>(admininfo);
}
} /// <summary>
/// 检查用户是否有该Action执行的操作权限
/// </summary>
/// <param name="actionContext"></param>
public override void OnActionExecuting(HttpActionContext actionContext)
{
////在action执行前终止请求时,应该使用填充方法Response,将不返回action方法体。
// actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK,new{a=actionContext.ControllerContext.Request.RequestUri.LocalPath});
//判断管理员是否存在
if (Model == null)
{
if (!actionContext.ControllerContext.Request.RequestUri.LocalPath.ToLower().Equals("/api/login/login"))
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
}
base.OnActionExecuting(actionContext);
}
}

BaseController

 [BasicAuthentication]
public class BaseController : ApiController
{
/// <summary>
/// 当前登录管理员信息
/// </summary>
public Admin AdminModel;
public BaseController()
{
//通过反射获取验证特性中的属性
Type tp = typeof(BaseController);
MemberInfo info = tp;
BasicAuthenticationAttribute basic = (BasicAuthenticationAttribute)Attribute.GetCustomAttribute(info, typeof(BasicAuthenticationAttribute));
AdminModel = basic.Model;
}
}
上一篇:Mysql 中获取刚插入的自增长id的值


下一篇:GPL 和BSD和Apache