Calling the Session before any Controller Action is run in MVC

天大地大妈咪最大 提交于 2019-12-20 06:29:59

问题


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

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

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.


回答1:


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

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

[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);
}

and in each controller:

public class AnotherNormalController : BaseController


来源:https://stackoverflow.com/questions/3263936/calling-the-session-before-any-controller-action-is-run-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!