在Asp Core 2视图内访问Session对象 [英] Accessing Session object inside an Asp Core 2 View
问题描述
我想在视图中显示会话.那可能吗? 我认为我可以尝试
I want to show Session in view. Is that possible? I try with this in my view
<div class="content-header col-xs-12">
<h1>Welcome, @HttpContext.Session.GetString("userLoggedName")</h1>
</div>
但是我得到一个错误
严重性代码描述项目文件行抑制状态错误 CS0120 非静态字段,方法或属性'HttpContext.Session'需要对象引用
Severity Code Description Project File Line Suppression State Error CS0120 An object reference is required for the non-static field, method, or property 'HttpContext.Session'
任何帮助,我将不胜感激.谢谢
Any help, i will appreciate it. Thanks
推荐答案
您可以将IHttpContextAccessor
实现注入到视图中,并使用它来获取Session对象
You can inject IHttpContextAccessor
implementation to your view and use it to get the Session object
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
<h1>@HttpContextAccessor.HttpContext.Session.GetString("userLoggedName")</h1>
假设您已经在Startup类中完成了用于启用会话的所有设置.
Assuming you already have everything setup for enabling session in the Startup class.
public void ConfigureServices(IServiceCollection services)
{
services.AddSession(s => s.IdleTimeout = TimeSpan.FromMinutes(30));
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession(); // This line is needed
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
这篇关于在Asp Core 2视图内访问Session对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!