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

查看:272
本文介绍了在任何Controller之前调用会话在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位于一个较旧的Webforms项目,我的MVC项目坐在那里。所以我相信它让我访问我的控制器动作,例如 http:// localhost / controller / action ,而不会填充我的会话身份验证,即不会重定向。我已经添加了这一点的代码到每个控制器动作来绕过这一点,但有一种方法来设置这个地方全局(不是在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.

推荐答案

您应该创建一个所有控制器继承的basecontroller。那么你只需要在一个地方的逻辑。即:

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,而不是初始化。这不是最优雅的地方,因为我们在被称为视图的尖端​​。

[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

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

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