C# 如何在 ASP.NET MVC 中处理会话数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/671228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:43:25  来源:igfitidea点击:

How to handle session data in ASP.NET MVC

c#asp.net-mvcsession

提问by Tom Maeckelberghe

Let's say I want to store a variable called language_idin the session. I thought I might be able to do something like the following:

假设我想存储一个language_id在会话中调用的变量。我想我可以做如下事情:

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

But when I check the session it's always null. How come? Where can I find some information about handling session in ASP.NET MVC?

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

回答by Richard

You may have to enable session within the web.config as well. Also there is an article on session state and state value here:

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

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

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

Hope this helps.

希望这可以帮助。

回答by bzlm

It should work, but is not a recommended strategy. Maybe session state is turned off in IIS or ASP.NET? See this answer and its comments.

它应该有效,但不是推荐的策略。也许会话状态在 IIS 或 ASP.NET 中已关闭?请参阅此答案及其评论

回答by Dan Atkinson

Not strictly related to the question itself, but more as a way of keeping controllers (reasonably) strongly typed and clean, I would also recommend a Session facade like class which wraps any session information in it, so that you read and write it in a nice way.

与问题本身并不严格相关,但更多的是作为一种保持控制器(合理)强类型和清洁的方式,我还建议使用一个 Session 门面,例如将任何会话信息包装在其中的类,以便您在其中读取和写入它不错的方式。

Example:

例子:

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

Usage:

用法:

public ActionResultChangelangue(FormCollection form)
{
  SessionFacade.CurrentLanguage = form["languageid"];
  return View();
}