標籤:
有些同學喜歡在測試或運行項目時,直接跳轉頁面到Home/Index下,但本次項目直接輸入Home/Index則會報錯
因為home/index中有個user.name參數,如果啟動項目後直接跳轉到home/index頁後,則會報錯。下面,我們來學習利用過濾器,直接輸入home/index後讓頁面跳轉到登入頁面。(注意:如果當前你在測試時,已經登入跳轉到首頁後,在登出之前再重新整理,輸入home/index地址時,並不會報錯,因為user.name參數是儲存在session中,而我們在登出的操作中才把session內容清空)
好,下面來構造過濾器。
1. 先在Controllers檔案夾下建立名為Filter的檔案夾,用來放過濾器的代碼,再添加一個名為CheckLoginFilter.cs的類檔案
2. 在CheckLoginFilter.cs中添加如下代碼:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace UserManager.Web.Controllers.Filter{ public class CheckLoginFilter : FilterAttribute, IActionFilter { public void OnActionExecuted(ActionExecutedContext filterContext) { if (HttpContext.Current.Session["user"] == null) { filterContext.HttpContext.Response.Write("-1"); } } public void OnActionExecuting(ActionExecutingContext filterContext) { if (HttpContext.Current.Session["user"] == null) { filterContext.Result = new RedirectResult("/Account/Index"); } } }}
3. 在控制器/HomeControllers.cs檔案中添加過濾器:
顯示結果:當運行項目,地址欄輸入Home/index時,馬上跳轉到Account/index的登入介面。
asp.net+mvc+easyui+sqlite 簡單使用者系統學習之旅(六)—— 簡單過濾器的使用