如今多數網站必須驗證用戶登錄並利用Session或者Cookie存儲用戶登錄後才能進行操做,session
若是存儲過時或者沒用登錄則自動返回到登錄界面,而MVC自帶AuthorizeAttribute屬性進行驗證。ide
一、 用戶登錄網站
輸入用戶登陸名和密碼驗證成功後,利用Session存儲登錄用戶信息url
HttpContext.Current.Session["LoginUser"] = userDTO;//userDTO登錄用戶實體類
二、建立AccountManagerment類下GetCurrentUser()方法,獲取Session中存儲的用戶信息,返回實體類UserDTOspa
public class AccountManagerment { /// <summary> /// 獲取當前用戶信息 /// </summary> /// <returns></returns> public static UserDTO GetCurrentUser() { var session = HttpContext.Current.Session["LoginUser"]; if (session == null) return new UserDTO(); return session as UserDTO; } }
三、建立AccountAuthorizeAttribute類,繼承AuthorizeAttribute,並重寫OnAuthorization方法code
/// <summary> /// 驗證用戶是否登陸 /// </summary> public class AccountAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext authorizationContext) { var httpContext = authorizationContext.HttpContext; var request = httpContext.Request; ActionResult actionResult = null; string message = string.Empty; var user = AccountManagerment.GetCurrentUser(); if (user.rolepermissionDTO == null) { String url = request.RawUrl; UrlHelper urlHelper = new UrlHelper(request.RequestContext); //利用Action 指定的操做名稱、控制器名稱和路由值生成操做方法的徹底限定 URL。 string returnUrl = urlHelper.Action("Login", "Home", new { returnUrl = "", message = message }); actionResult = new RedirectResult(returnUrl); } authorizationContext.Result = actionResult; } }
四、將屬性[AccountAuthorize]置於整個Controller之上。當用戶有操做時,進入控制器前都會先驗證用戶是否登陸,或者存儲用戶信息過時從而返回登陸界面。blog
[AccountAuthorize] public ActionResult Index(string title, string dp, string end, int id = 1) { return view(); }