我们知道,要在一个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); } }
比如发生错误的时候跳转到新浪首页:
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")]