如何处理在ASP.NET MVC中的会话数据 [英] How to handle session data in ASP.NET MVC
问题描述
比方说,我要存储一个名为 LANGUAGE_ID
在会话变量。我想我也许可以做类似以下内容:
Let's say I want to store a variable called language_id
in the session. I thought I might be able to do something like the following:
public class CountryController : Controller
{
[WebMethod(EnableSession = true)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResultChangelangue(FormCollection form)
{
Session["current_language"] = form["languageid"];
return View();
}
}
但是,当我检查会话它总是空。怎么来的?我在哪里可以找到有关ASP.NET MVC处理会话的一些信息?
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?
推荐答案
的不严格相关的问题本身的,但更多的是保持控制器(合理的)强类型的,干净的,我会的一种方式还建议会话外观像类包装在其中的任何会话信息,让你阅读和在一个很好的方式写。
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.
示例:
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();
}
这篇关于如何处理在ASP.NET MVC中的会话数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!