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的登录界面。

 

转载于:https://www.cnblogs.com/jennyjiang-00/p/5760304.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值