namespace MVCAuthorizeTest.Controllers { public class LoginController : Controller { [AllowAnonymous] // GET: Login public ActionResult Index(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } [HttpPost] [AllowAnonymous] public ActionResult Index(string name, string password, bool rememberMe, string returnUrl) { var account = new UserData() { UserName = name, UserId = 110, Roles = new List<int>() { 1, 2, 3 } }; HttpFormsAuthentication.SetAuthenticationCoolie(account, rememberMe ? 7 : 0); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("https://www.jb51.net/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } // POST: /Account/LogOff [HttpPost] public ActionResult LogOff() { System.Web.Security.FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); } } }
7.对需要验证的controller或action添加特性标签
[FormAuthorize(Roles = "1,2")] public class HomeController : Controller { [FormAuthorize] public ActionResult Index() { return View(); } }
如图
8.在添加FilterConfig中添加全局注册filter,减少每个action分别设置。如果有不需要验证的页面,添加[AllowAnonymous]特性即可
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); //全局注册filter filters.Add(new FormAuthorizeAttribute()); } }