MVC4項目中驗證使用者登入一個特性就搞定

來源:互聯網
上載者:User

標籤:

在開發過程中,需要使用者登陸才能訪問指定的頁面這種功能,微軟已經提供了這個特性。    // 摘要:    //     表示一個特性,該特性用於限制調用方對操作方法的訪問。    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]    public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter但是,美中不足的是,需要微軟內建的一些使用者驗證的東西,比如資料庫,配置等等的。常常我們只需要用SESSION或者Cookies去儲存使用者登入狀態的時候,這豈不是殺雞用牛刀的感覺?那麼,我們按照微軟官方的這個特性,重寫一個屬於自己的驗證屬性類別就行了。下面是我常用的自己寫的一段代碼,希望大家用得開心,如果有異議可以自己修改,代碼無著作權,哈哈,我們只為共用。下面也提供了一個可以直接引用的DLL,需要.NET 4.0 Framework的支援。:點擊這裡下載代碼:using System.Web.Mvc;namespace System{    /// <summary>    /// 表示需要使用者登入才可以使用的特性    /// <para>如果不需要處理使用者登入,則請指定AllowAnonymousAttribute屬性</para>    /// </summary>    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]    public class AuthorizationAttribute : FilterAttribute, IAuthorizationFilter    {        /// <summary>        /// 預設建構函式        /// </summary>        public AuthorizationAttribute()        {            String authUrl = System.Configuration.ConfigurationManager.AppSettings["AuthUrl"];            String saveKey = System.Configuration.ConfigurationManager.AppSettings["AuthSaveKey"];            String saveType = System.Configuration.ConfigurationManager.AppSettings["AuthSaveType"];            if (String.IsNullOrEmpty(authUrl))            {                this._AuthUrl = "/User/Login";            }            else            {                this._AuthUrl = authUrl;            }            if (String.IsNullOrEmpty(saveKey))            {                this._AuthSaveKey = "LoginedUser";            }            else            {                this._AuthSaveKey = saveKey;            }            if (String.IsNullOrEmpty(saveType))            {                this._AuthSaveType = "Session";            }            else            {                this._AuthSaveType = saveType;            }        }        /// <summary>        /// 建構函式重載        /// </summary>        /// <param name="loginUrl">表示沒有登入跳轉的登入地址</param>        public AuthorizationAttribute(String authUrl)            : this()        {            this._AuthUrl = authUrl;        }        /// <summary>        /// 建構函式重載        /// </summary>        /// <param name="loginUrl">表示沒有登入跳轉的登入地址</param>        /// <param name="saveKey">表示登入用來儲存登陸資訊的鍵名</param>        public AuthorizationAttribute(String authUrl, String saveKey)            : this(authUrl)        {            this._AuthSaveKey = saveKey;            this._AuthSaveType = "Session";        }        /// <summary>        /// 建構函式重載        /// </summary>        /// <param name="authUrl">表示沒有登入跳轉的登入地址</param>        /// <param name="saveKey">表示登入用來儲存登陸資訊的鍵名</param>        /// <param name="saveType">表示登入用來儲存登陸資訊的方式</param>        public AuthorizationAttribute(String authUrl, String saveKey, String saveType)            : this(authUrl, saveKey)        {            this._AuthSaveType = saveType;        }        private String _AuthUrl = String.Empty;        /// <summary>        /// 擷取或者設定一個值,改值表示登入地址        /// <para>如果web.config中未定義AuthUrl的值,則預設為/User/Login</para>        /// </summary>        public String AuthUrl        {            get { return _AuthUrl.Trim(); }            set            {                if (String.IsNullOrEmpty(value))                {                    throw new ArgumentNullException("用於驗證使用者登入資訊的登入地址不可為空!");                }                else                {                    _AuthUrl = value.Trim();                }            }        }        private String _AuthSaveKey = String.Empty;        /// <summary>        /// 擷取或者設定一個值,改值表示登入用來儲存登陸資訊的鍵名        /// <para>如果web.config中未定義AuthSaveKey的值,則預設為LoginedUser</para>        /// </summary>        public String AuthSaveKey        {            get { return _AuthSaveKey.Trim(); }            set            {                if (String.IsNullOrEmpty(value))                {                    throw new ArgumentNullException("用於儲存登陸資訊的鍵名不可為空!");                }                else                {                    this._AuthSaveKey = value.Trim();                }            }        }        private String _AuthSaveType = String.Empty;        /// <summary>        /// 擷取或者設定一個值,該值表示用來儲存登陸資訊的方式        /// <para>如果web.config中未定義AuthSaveType的值,則預設為Session儲存</para>        /// </summary>        public String AuthSaveType        {            get { return _AuthSaveType.Trim().ToUpper(); }            set            {                if (String.IsNullOrEmpty(value))                {                    throw new ArgumentNullException("用於儲存登陸資訊的方式不可為空,只能為【Cookie】或者【Session】!");                }                else                {                    _AuthSaveType = value.Trim();                }            }        }        /// <summary>        /// 處理使用者登入        /// </summary>        /// <param name="filterContext"></param>        public void OnAuthorization(AuthorizationContext filterContext)        {            if (filterContext.HttpContext == null)            {                throw new Exception("此特性只適合於Web應用程式使用!");            }            else            {                switch (AuthSaveType)                {                    case "SESSION":                        if (filterContext.HttpContext.Session == null)                        {                            throw new Exception("伺服器Session不可用!");                        }                        else if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))                        {                            if (filterContext.HttpContext.Session[_AuthSaveKey] == null)                            {                                filterContext.Result = new RedirectResult(_AuthUrl);                            }                        }                        break;                    case "COOKIE":                        if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))                        {                            if (filterContext.HttpContext.Request.Cookies[_AuthSaveKey] == null)                            {                                filterContext.Result = new RedirectResult(_AuthUrl);                            }                        }                        break;                    default:                        throw new ArgumentNullException("用於儲存登陸資訊的方式不可為空,只能為【Cookie】或者【Session】!");                }            }        }    }}然後在Web.Config檔案裡面加入下面幾句用於配置登陸驗證的一些資訊:  <appSettings>    <add key="AuthUrl" value="/User/Login" />    <add key="AuthSaveKey" value="LoginedUser" />    <add key="AuthSaveType" value="Session" />  </appSettings>使用執行個體://...省略引用namespace MrHuo.Framework.Blog{    [Authorization]//如果將此特性加在Controller上,那麼訪問這個Controller裡面的方法都需要驗證使用者登入狀態    public class UserController:Controller    {        [AllowAnonymous]//這裡是一個特例,有這個特性,表示這個方法不需要驗證使用者登入狀態        public ActionResult Index()        {            //...省略具體代碼        }        //這裡的方法需要驗證登入狀態,以下雷同        public ActionResult Create()        {            //...省略具體代碼        }    }}

MVC4項目中驗證使用者登入一個特性就搞定

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.