Thu*_*gwe 104 asp.net-mvc session session-variables asp.net-mvc-4
我是ASP.NET MVC的新手.我之前使用过PHP,很容易创建会话并根据当前会话变量选择用户记录.
我在互联网上到处寻找一个简单的分步教程,可以向我展示如何在我的C#ASP.NET MVC 4应用程序中创建和使用会话.我想创建一个包含用户变量的会话,我可以从我的控制器中的任何位置访问它,并且能够在我的LINQ查询中使用变量.
-提前致谢!
Job*_*mno 153
尝试
//adding data to session
//assuming the method below will return list of Products
var products=Db.GetProducts();
//Store the products to a session
Session["products"]=products;
//To get what you have stored to a session
var products=Session["products"] as List<Product>;
//to clear the session value
Session["products"]=null;
Run Code Online (Sandbox Code Playgroud)
Jos*_*ard 61
由于Web的无状态特性,会话也是一种非常有用的方法,可以通过将对象序列化并将它们存储在会话中来跨对请求来保持对象.
一个完美的用例可能是,如果您需要访问整个应用程序的常规信息,为每个请求保存额外的数据库调用,这些数据可以存储在一个对象中并在每个请求上反序列化,如下所示:
我们可重用,可序列化的对象:
[Serializable]
public class UserProfileSessionData
{
public int UserId { get; set; }
public string EmailAddress { get; set; }
public string FullName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
使用案例:
public class LoginController : Controller {
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
var profileData = new UserProfileSessionData {
UserId = model.UserId,
EmailAddress = model.EmailAddress,
FullName = model.FullName
}
this.Session["UserProfile"] = profileData;
}
}
public ActionResult LoggedInStatusMessage()
{
var profileData = this.Session["UserProfile"] as UserProfileSessionData;
/* From here you could output profileData.FullName to a view and
save yourself unnecessary database calls */
}
}
Run Code Online (Sandbox Code Playgroud)
一旦该对象被序列化,我们就可以在所有控制器中使用它,而无需创建它或再次查询数据库中包含的数据.
使用依赖注入注入会话对象
在一个理想的世界中,你将" 编程到一个接口,而不是实现 ",并使用你选择的Inversion of Control容器将可序列化的会话对象注入你的控制器,就像这样(这个例子使用StructureMap,因为它是我最熟悉的那个) ).
public class WebsiteRegistry : Registry
{
public WebsiteRegistry()
{
this.For<IUserProfileSessionData>().HybridHttpOrThreadLocalScoped().Use(() => GetUserProfileFromSession());
}
public static IUserProfileSessionData GetUserProfileFromSession()
{
var session = HttpContext.Current.Session;
if (session["UserProfile"] != null)
{
return session["UserProfile"] as IUserProfileSessionData;
}
/* Create new empty session object */
session["UserProfile"] = new UserProfileSessionData();
return session["UserProfile"] as IUserProfileSessionData;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在您的Global.asax.cs
文件中注册.
对于那些不熟悉注入会话对象的人,您可以在此处找到有关该主题的更深入的博客文章.
一句警告:
值得注意的是,会话应该保持在最低限度,大型会话可能会导致性能问题.
还建议不要在其中存储任何敏感数据(密码等).
Len*_*rri 17
这是会话状态在ASP.NET和ASP.NET MVC中的工作方式:
基本上,这样做是为了在Session对象中存储一个值:
Session["FirstName"] = FirstNameTextBox.Text;
Run Code Online (Sandbox Code Playgroud)
要检索值:
var firstName = Session["FirstName"];
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
391924 次 |
最近记录: |