我们知道,要在一个action前加上权限的限制就要特性比如拥有admin权限的用户就加上
[Authorize(Roles="admin")]
给每个登陆用户分配权限则是要在Global.asax.cs中加上这两个函数
public MvcApplication()
{
AuthorizeRequest += new EventHandler(MvcApplication_AuthorizeRequest);
}
void MvcApplication_AuthorizeRequest(object sender, EventArgs e)
{
IIdentity id = Context.User.Identity;
if (id.IsAuthenticated)
{
var roles = new string[] { "admin", "reg" };
//string[] rolelist = new string[] { roles.Name };
Context.User = new GenericPrincipal(id, roles);
}
}
当权限验证失败时,mvc默认跳转到登陆页面,如果我们要改变这一设置就要重载Attribute 类:System.Web.Mvc.AuthorizeAttribute的HandleUnauthorizedRequest函数
比如发生错误的时候跳转到新浪首页:
public class MyAuth : System.Web.Mvc.AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
//base.HandleUnauthorizedRequest(filterContext);
filterContext.HttpContext.Response.Redirect("http://www.sina.com");
}
}
别忘了在action前面加上自己定义的权限特性:
[MyAuth(Roles = "admin")]