一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

asp.net中mvc验证用户登录的例子

时间:2014-04-19 编辑:简简单单 来源:一聚教程网

因此一般我都是把AcountController的相关的东西都删了,一步一步自己来重建自己的登陆模块。

MVC提供了四种Filter(钩子),用于在Action执行之前或者之后,我们能够做一些事情,比如说判断有没有登录,比如说判断有没有权限。

IAuthorizationFilter:在所有Filter和Action执行之前执行

IActionFilter:分别在Action执行之前和之后执行。

IResultFilter:分别在Action Result执行之后和之前

IExceptionFilter:只有在filter,或者 action method, 或者 action result 抛出一个异常时候执行

做登录验证,用IAuthorizationFilter应该是最好的选择,比如系统自带的登陆与权限验证,就是用这个做的。但是我们今天要讲的是如何用ActionFilter做登录的验证。

我们转到Controller的定义的时候,发现是这样子的:

public abstract class Controller : ControllerBase, IActionFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter, IAsyncController, IController, IAsyncManagerContainer

看到IActionFilter接口了木有,这让我们找到一个思路:新建一个基类,在该类中重载OnActionExecuting方法,这样子整个在所有Action执行之前都会先判断权限了:

 代码如下 复制代码

public class BaseController : Controller

    {


        // GET: /Base/


        protected override void OnActionExecuting(ActionExecutingContext filterContext)

        {

            if (filterContext.HttpContext.Request.Cookies["UserID"] == null)

            {

                if (this.RouteData.Values["Controller"].ToString() != "Login" )

                {

                    //跳转到登陆页

                    filterContext.Result = new RedirectResult("/Login/Index");

                }

            }

            base.OnActionExecuting(filterContext);

        }

 

    }

如上代码通过判断Cookies中的UserID来判断用户是否登陆,如果没有登陆,就跳转到Login/Index中去。你将其它所有需要验证登陆的controller继承自baseController就可以实现判断登陆了。

但是LoginController只能够直接继承自Controller,否则程序判断你没有登陆,然后跳转到Login,但是在Login实现Index之前,程序判断你仍然没有登陆,于是又跳转到Login,实现了一个死循环。

下面也提供了一个可以直接引用的DLL,需要.NET 4.0 Framework的支持。

代码:

 代码如下 复制代码

using System.Web.Mvc;

namespace System
{
    ///


    /// 表示需要用户登录才可以使用的特性
    /// 如果不需要处理用户登录,则请指定AllowAnonymousAttribute属性
    ///

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class AuthorizationAttribute : FilterAttribute, IAuthorizationFilter
    {
        ///
        /// 默认构造函数
        ///

        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;
            }
        }
        ///


        /// 构造函数重载
        ///

        /// 表示没有登录跳转的登录地址
        public AuthorizationAttribute(String authUrl)
            : this()
        {
            this._AuthUrl = authUrl;
        }
        ///
        /// 构造函数重载
        ///

        /// 表示没有登录跳转的登录地址
        /// 表示登录用来保存登陆信息的键名
        public AuthorizationAttribute(String authUrl, String saveKey)
            : this(authUrl)
        {
            this._AuthSaveKey = saveKey;
            this._AuthSaveType = "Session";
        }
        ///
        /// 构造函数重载
        ///

        /// 表示没有登录跳转的登录地址
        /// 表示登录用来保存登陆信息的键名
        /// 表示登录用来保存登陆信息的方式
        public AuthorizationAttribute(String authUrl, String saveKey, String saveType)
            : this(authUrl, saveKey)
        {
            this._AuthSaveType = saveType;
        }

        private String _AuthUrl = String.Empty;
        ///


        /// 获取或者设置一个值,改值表示登录地址
        /// 如果web.config中未定义AuthUrl的值,则默认为/User/Login
        ///

        public String AuthUrl
        {
            get { return _AuthUrl.Trim(); }
            set
            {
                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException("用于验证用户登录信息的登录地址不能为空!");
                }
                else
                {
                    _AuthUrl = value.Trim();
                }
            }
        }

        private String _AuthSaveKey = String.Empty;
        ///


        /// 获取或者设置一个值,改值表示登录用来保存登陆信息的键名
        /// 如果web.config中未定义AuthSaveKey的值,则默认为LoginedUser
        ///

        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;
        ///


        /// 获取或者设置一个值,该值表示用来保存登陆信息的方式
        /// 如果web.config中未定义AuthSaveType的值,则默认为Session保存
        ///

        public String AuthSaveType
        {
            get { return _AuthSaveType.Trim().ToUpper(); }
            set
            {
                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException("用于保存登陆信息的方式不能为空,只能为【Cookie】或者【Session】!");
                }
                else
                {
                    _AuthSaveType = value.Trim();
                }
            }
        }

        ///


        /// 处理用户登录
        ///

        ///
        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文件里面加入下面几句用于配置登陆验证的一些信息:
 
   
   
   
 

使用实例:
//...省略引用
namespace MrHuo.Framework.Blog
{
    [Authorization]//如果将此特性加在Controller上,那么访问这个Controller里面的方法都需要验证用户登录状态
    public class UserController:Controller
    {
        [AllowAnonymous]//这里是一个特例,有这个特性,表示这个方法不需要验证用户登录状态
        public ActionResult Index()
        {
            //...省略具体代码
        }
        //这里的方法需要验证登录状态,以下雷同
        public ActionResult Create()
        {
            //...省略具体代码
        }
    }
}

热门栏目