在MVC系统开发中,难免会遇到权限验证问题,解决这个问题的方法很多,这里使用自定义AuthorizeAttribute来实现,代码如下:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.Request.Cookies["yourset"] == null)
return false;
return base.AuthorizeCore(httpContext);
//bool result = false;
//if (httpContext == null)
//{
// throw new ArgumentNullException("httpContext");
//}
//string[] users = Users.Split(',');
//string[] roles = Roles.Split(',');
//if (!httpContext.User.Identity.IsAuthenticated)
// return false;
//if (roles.Length != 0)
//{
// // we can get the roles by our bussiness logic here
// List<string> rightRoles = new List<string> { "admin", "owner" };
// foreach (var role in roles)
// {
// if (rightRoles.Contains(role))
// {
// result = true;
// break;
// }
// }
//}
//if (!result)
//{
// httpContext.Response.StatusCode = 403;
//}
//return result;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.HttpContext.Response.StatusCode == 403)
{
filterContext.Result = new RedirectResult("/Home/Index");
}
}
}
这样,我们就可以在我们的Action上用它来设置访问权限了。