如何从 ASP .NET Core MVC 1.0 中的视图访问会话

How to access session from a view in ASP .NET Core MVC 1.0

我正在尝试从视图内部访问会话数据。

用例: 我将状态消息存储在将显示在页面顶部的会话中。目前,我通过使用设置一些 ViewData[....] 属性并在每个控制器操作开始时调用它的 DisplayMessages() 函数来实现它。

目标:我只想设置一次状态消息,而无需在控制器中添加额外代码以在下一页加载时显示消息。

所以我尝试直接从视图访问存储在会话中的消息。

到目前为止,我已经尝试了以下方法:

以下应该在视图中起作用:Context.Session.TryGetValue

如果您使用的是 SessionExtensions,则 Context.Session.GetString 可以。

注入 IHttpContextAccessor 确实有效,但是从 ASP.NET Core 1.0.0 RC2 开始,IHttpContextAcessor 默认情况下不会注册,因为它对每个请求都有显着的性能开销。有关详细信息,请参阅 this GitHub announcement

Tracher 发布:

IHttpContextAccessor can be used to access the HttpContext for the current thread. However, maintaining this state has non-trivial performance costs so it has been removed from the default set of services.

Developers that depend on it can add it back as needed: services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

但在您的用例中,我建议使用 ViewComponent,这是一个可重复使用的具有逻辑的 View,不依赖于控制器。

可以找到文档 here

在您的视图中,您只需将其嵌入

@await Component.InvokeAsync("PriorityList", new { maxPriority = 2, isDone = false })

@Component.Invoke("PriorityList", new { maxPriority = 2, isDone = false })

用于同步调用。