asp.net+mvc+easyui+sqlite 簡單使用者系統學習之旅(六)—— 簡單過濾器的使用

來源:互聯網
上載者:User

標籤:

有些同學喜歡在測試或運行項目時,直接跳轉頁面到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 簡單使用者系統學習之旅(六)—— 簡單過濾器的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.