C# 如何在ASP.NET MVC中处理会话数据
假设我想在会话中存储一个名为C# 如何在ASP.NET MVC中处理会话数据,c#,asp.net-mvc,session,C#,Asp.net Mvc,Session,假设我想在会话中存储一个名为language\u id的变量。我想我可能可以做如下事情: public class CountryController : Controller { [WebMethod(EnableSession = true)] [AcceptVerbs(HttpVerbs.Post)] public ActionResultChangelangue(FormCollection form) { Session["cu
language\u 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中处理会话的信息?您可能还需要在web.config中启用会话。这里还有一篇关于会话状态和状态值的文章:
希望这能有所帮助。它应该会起作用,但不是推荐的策略。可能IIS或ASP.NET中的会话状态已关闭?请参阅。与问题本身没有严格的关系,但更重要的是,作为保持控制器(合理地)强类型和干净的一种方式,我还建议使用一个类似会话facade的类,它将任何会话信息封装在其中,以便您以一种良好的方式读写它 示例:
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();
}
用法:
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();
}
[WebMethod]不是仅用于ASP.NET web服务吗?您能否向我们展示从会话中访问变量的代码,因为您只展示了设置值的代码?还要记住,在问题的开头,您提到了一个名为
language\u id
的变量,但设置会话的代码提到了一个languageid
变量(无下划线)。