asp.net+mvc+easyui+sqlite 简单用户系统学习之旅(六)—— 简单过滤器的使用

有些同学喜欢在测试或运行项目时,直接跳转页面到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的登录界面。

 

posted @ 2016-08-11 11:24  JennyJiang  阅读(616)  评论(0编辑  收藏  举报