检查会话的控制器的所有动作 [英] Check Session on all actions of controller

查看:51
本文介绍了检查会话的控制器的所有动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的MVC应用程序 我想先检查一下该会话

I have an simple MVC app I want to check first the session as this action

 public ActionResult Index()
        {
            if (Session["UserInfo"] == null)
            {
              return  RedirectToAction("Login", "Users");
            }
            return View();
        }

我的问题是关于 有没有一种方法可以对所有操作强制执行此检查,而无需为每个操作手动执行?

My question is about is there a way to enforce this check to all actions without do it manual for each action?

推荐答案

您可以使用OnActionExecuting,也可以重写此方法来编写自定义逻辑,因此可以创建一个类

you can use OnActionExecuting and can also override this method to write custom logic so create a class

 public class SessionCheck: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpSessionStateBase session = filterContext.HttpContext.Session;
            if (session != null && session["UserInfo"] == null)
            {
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary {
                                { "Controller", "Users" },
                                { "Action", "Login" }
                                });
            }
        }
    } 

在类中添加名称空间

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

,然后在您的控制器中添加[SessionCheck]这样的属性

and in your controller add [SessionCheck] attribute like this

 [SessionCheck]
 public class HomeController : Controller
  {
  }

这将检查控制器所有动作的会话,或者您也可以在这样的动作上添加此属性

this will check session on all the actions of controller or you can also add this attribute on action like this

[SessionCheck]
public ActionResult Index()
 {
 } 

这篇关于检查会话的控制器的所有动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆