在 MVC 中运行任何控制器操作之前调用会话 [英] Calling the Session before any Controller Action is run in MVC

查看:20
本文介绍了在 MVC 中运行任何控制器操作之前调用会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Session_OnStart() 调用中的 global.asax 文件中进行了此身份验证检查:

I have this authentication check in my global.asax file in the Session_OnStart() call:

if (Session["Authenticated"] == null)
        {
            Response.Redirect("~/Login.aspx");
        }

这种会话身份验证在我们所有的网络应用程序中都是紧密耦合的,所以我必须以这种方式使用它.这个 global.asax 位于我的 MVC 项目所在的旧 Webforms 项目中.因此,我相信它可以让我访问我的控制器操作,例如 http://localhost/controller/action 直接没有填充我的会话身份验证,即它不重定向.我已将这段代码添加到 EACH 控制器操作中以解决此问题,但是有没有办法将其设置在全局某处(不是在 global.asax 中),以便我只需为所有控制器操作调用一次?谢谢.

This kind of session authentication is tightly coupled in all our web apps so I have to use it this way. This global.asax sits in an older Webforms project, which my MVC project is sitting in. So for this reason I believe its letting me access my controller action e.g http://localhost/controller/action directly without my session authentication being populated, i.e its not redirecting. I have added this bit of code to EACH controller action to get around this, but is there a way to set this somewhere globally (not in the global.asax) so that I only have to call it once for all controller actions? Thanks.

推荐答案

您应该创建一个所有控制器都继承自的基本控制器.那么您只需将逻辑集中在一处.即:

You should create a basecontroller that all your controllers inherit from. then you simply have the logic in one place. i.e.:

public abstract class BaseController : ControllerBase

然后您可以使用新 BaseContoller 中的 initialize 方法来执行通用逻辑.即

you could then use the initialize method in the new BaseContoller to do the common logic. i.e.

[edit] - 更改为 OnActionExecuting,而不是 Initialize.这不是最优雅的地方,因为我们正处于被调用的视图的风口浪尖.然而,这是一个起点.

[edit] - changed to OnActionExecuting, rather than Initialize. This isn't the most elegant of places to do it as we're on the cusp of the view being called. however, it's a starting point.

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    // you should be able to get session stuff here!!
    base.OnActionExecuting(filterContext);
}

并在每个控制器中:

public class AnotherNormalController : BaseController

这篇关于在 MVC 中运行任何控制器操作之前调用会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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