如何从ASP .NET Core MVC 1.0中的视图访问会话 [英] How to access session from a view in ASP .NET Core MVC 1.0
问题描述
我正在尝试从视图内部访问会话数据.
I am trying to access session data from inside a view.
用例::我将状态消息存储在将显示在页面顶部的会话中.目前,我是通过使用DisplayMessages()
函数来实现此功能的,该函数设置一些ViewData[....]
属性,并在每个控制器操作的开始处调用它.
Use Case: I'm storing status messages in the session that will be displayed at the top of the page. Currently I implemented this by using a DisplayMessages()
function that sets some ViewData[....]
properties and calling it at the beginning of every controller action.
目标:我只想设置一次状态消息,而无需控制器中的其他代码即可在下一页加载时显示该消息.
Goal: I want to only set the status message once without needing additional code in the controller to display the messages on the next page load.
因此,我试图直接从视图访问会话中存储的消息.
So I'm trying to access the messages that are stored in the session directly from the view.
到目前为止,我已经尝试了以下方法:
So far I have tried the following:
-
IHttpContextAccessor的
- 依赖项注入(似乎不再与ASP .NET Core MVC 1.0.0一起工作
- 创建用于访问会话的静态类,包括在建议中将
next()
更改为next.invoke()
评论- 这没有用.我可以访问
HttpContext
,并且Session.IsAvailable
是正确的,但是会话中没有数据.
- Dependency Injection of an IHttpContextAccessor (doesn't seem to work anymore with ASP .NET Core MVC 1.0.0
- Creating a static class to access the session, including the change from
next()
tonext.invoke()
suggested in the comment- This didn't work. I could access the
HttpContext
andSession.IsAvailable
was true, but there was no data in the session.
推荐答案
以下内容应在视图中起作用:
Context.Session.TryGetValue
The following should work in the view:
Context.Session.TryGetValue
如果您使用的是
SessionExtensions
,则Context.Session.GetString
将起作用.If you are using the
SessionExtensions
thenContext.Session.GetString
will work.这篇关于如何从ASP .NET Core MVC 1.0中的视图访问会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- This didn't work. I could access the
- 这没有用.我可以访问