如何在ASP.NET 5 MVC6中的布局文件中获取会话值 [英] How to get a session value in layout file in ASP.NET 5 MVC6
问题描述
在ASP.NET 5 MVC 6 Beta 8中,我需要在_Layout.cshtml
中读取会话变量,或者获取对当前HttpContext的引用.
In ASP.NET 5 MVC 6 Beta 8 I need to read a session variable in in my _Layout.cshtml
or alternatively get a reference to the current HttpContext.
Take note: In ASP.NET 5 referencing the Session object has changed significantly from ASP.net 4 as detailed in this question
Context
对象在Beta7和Beta8之间也已重命名为HttpContext
.
The Context
object has also been renamed to HttpContext
between Beta7 and Beta8.
在我当前的控制器中,我目前这样保存会话变量
In My current controller I currently save the session variable like this
public IActionResult Index()
{
HttpContext.Session.SetInt32("Template", (id));
}
在我的_Layout.cshtml中,我需要阅读上述会话变量. 我需要以某种方式引用当前的HttpContext,例如
In my _Layout.cshtml I need to read the above session variable. I need to reference the current HttpContext somehow e.g
HttpContext.Current.Session.GetInt32("Template");
但是我不知道如何在cshtml文件中获取当前的HttpContext.
but I don't know how to the get the current HttpContext in a cshtml file.
推荐答案
Context
和HttpContext
之间的命名有些混乱.您可以使用Context
属性在视图中访问HttpContext:
The naming between Context
and HttpContext
is somewhat confusing. You can access the HttpContext in a view using the Context
property:
@{ int x = Context.Session.GetInt32("test"); }
MVC存储库中还有一个与此相关的待解决问题: https://github.com/aspnet/Mvc/Issues/3332
There is also a pending issue at the MVC repo regarding this: https://github.com/aspnet/Mvc/issues/3332
这篇关于如何在ASP.NET 5 MVC6中的布局文件中获取会话值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!