代码之家  ›  专栏  ›  技术社区  ›  Tom Maeckelberghe

如何在asp.net mvc中处理会话数据

  •  2
  • Tom Maeckelberghe  · 技术社区  · 15 年前

    假设我想存储一个名为 language_id 在会议上。我想我可以做如下事情:

    public class CountryController : Controller
    { 
        [WebMethod(EnableSession = true)]  
        [AcceptVerbs(HttpVerbs.Post)]  
        public ActionResultChangelangue(FormCollection form)
        {
            Session["current_language"] = form["languageid"];
            return View();    
        } 
    }
    

    但当我检查会话时,它总是空的。为什么?在哪里可以找到有关在ASP.NET MVC中处理会话的信息?

    3 回复  |  直到 12 年前
        1
  •  12
  •   Dan Atkinson    15 年前

    与问题本身无关 ,但作为保持控制器(合理地)强类型和干净的一种方法,我还建议使用一个类似于会话外观的类,该类将任何会话信息包装在其中,以便您以良好的方式读写它。

    例子:

    public static class SessionFacade
    {
      public static string CurrentLanguage
      {
        get
        {
          //Simply returns, but you could check for a null
          //and initialise it with a default value accordingly...
          return HttpContext.Current.Session["current_language"].ToString();
        }
        set
        {
          HttpContext.Current.Session["current_language"] = value;
        }
      }
    }
    

    用途:

    public ActionResultChangelangue(FormCollection form)
    {
      SessionFacade.CurrentLanguage = form["languageid"];
      return View();
    } 
    
        2
  •  1
  •   Community leo1    7 年前

    它应该有效,但不是推荐的策略。在IIS或ASP.NET中,会话状态可能已关闭?见 this answer and its comments .

        3
  •  0
  •   Richard    15 年前

    您可能还必须在web.config中启用会话。这里还有一篇关于会话状态和状态值的文章:

    http://www.davidhayden.com/blog/dave/archive/2008/02/06/ASPNETMVCFrameworkSessionStateStateValueWCSF.aspx

    希望这有帮助。