65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET MVC 中的 Session

2014年6月27日

CPOL

2分钟阅读

viewsIcon

183911

downloadIcon

2887

ASP.NET MVC 中的 Session

引言

在 Web 应用程序中,我们使用 Session 来

  1. 检查用户是否已登录
  2. 保存权限信息
  3. 保存临时数据

有时,我们可能需要频繁使用保存的 Session 对象。在这里,我们将尝试在一个基础控制器中集中我们的 Session 工具,以便我们可以以最少的努力从其他控制器中使用 Session 对象。

背景

在开始之前,我们需要考虑一些事项,例如

  1. 我们将为整个 Web 项目使用单个 Session,这是一个好的做法。
  2. 如果控制器依赖于 Session 并且 Session 为 null,我们将重定向到登录页面。
  3. 并非所有控制器都依赖于 Session,例如 LogOnController ErrorController。因此,如果 Session 为 null,它将不会重定向到登录页面,而是渲染其默认页面。

Using the Code

这是我们应用程序的基础控制器,它处理 Session 工具。TSource 是我们想要保存到 Session 中的 Model 类型。现在,我们可以用两种方式使用它。

  1. 如果控制器不依赖于 Session,我们只需避免继承即可。
  2. 如果控制器不依赖于 Session,但我们正在从基础控制器继承。

那么 IsNonsessionController 方法中的 nonsessionedController 列表就很重要,我们需要在其中指定哪些控制器不依赖于 Session。

public class ApplicationController<TSource> : Controller
{
    private const string LogOnSession = "LogOnSession";  //session index name
    private const string ErrorController = "Error";      //session independent controller
    private const string LogOnController = "LogOn";      //session independent and LogOn controller    
    private const string LogOnAction = "LogOn";          //action to rederect

    protected ApplicationController()
    {           
    }

    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);
        /*important to check both, because logOn and error Controller should be access able with out any session*/
        if (!IsNonSessionController(requestContext) && !HasSession())
        {
            //Rederect to logon action
            Rederect(requestContext, Url.Action(LogOnAction, LogOnController)); 
        }
    }

    private bool IsNonSessionController(RequestContext requestContext)
    {
        var currentController = requestContext.RouteData.Values["controller"].ToString().ToLower();
        var nonSessionedController = new List<string>() {ErrorController.ToLower(), LogOnController.ToLower()};
        return nonSessionedController.Contains(currentController);
    }

    private void Rederect(RequestContext requestContext, string action)
    {
        requestContext.HttpContext.Response.Clear();
        requestContext.HttpContext.Response.Redirect(action);
        requestContext.HttpContext.Response.End();
    }

    protected bool HasSession()
    {
        return Session[LogOnSession] != null;
    }

    protected TSource GetLogOnSessionModel()
    {
        return (TSource)this.Session[LogOnSession];
    }

    protected void SetLogOnSessionModel(TSource model)
    {
        Session[LogOnSession] = model;
    }

    protected void AbandonSession()
    {
        if (HasSession())
        {
            Session.Abandon();
        }
    }
}

这里 LogOnModel 是可以设置为 Session 的模型。在每个控制器中,我们将像这样使用基础控制器,如果控制器想要处理 Session。

public class LogOnController : ApplicationController<LogOnModel>
{
}

要设置 Session、在注销时销毁它,或从任何子控制器获取 Session,我们需要像这样使用它:

/*Set model to session*/
LogOnModel model = new LogOnModel();
SetLogOnSessionModel(model);

/*destroy current session*/
AbandonSession();

/*Shows the session*/
LogOnModel sessionModel = GetLogOnSessionModel();

限制

在这里,我们只处理单个 Session。但是,您的应用程序可能需要处理多个 Session。为此,我们需要进行一些更改。如果您需要类似的功能,请联系我,我已经创建了一个用于此目的的程序。如果我有时间,我将在一周内发布它。

请查找项目附件,它是一个 VS 2010 解决方案,包含 MVC3 项目。

© . All rights reserved.