c# - 在 Asp Core 2 View 中访问 Session 对象

标签 c# asp.net-mvc razor asp.net-core asp.net-core-2.0

我想在 View 中显示 session 。那可能吗? 在我看来,我尝试这样做

<div class="content-header col-xs-12">
   <h1>Welcome, @HttpContext.Session.GetString("userLoggedName")</h1>
</div>

但是我得到一个错误

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'

任何帮助,我将不胜感激。谢谢

最佳答案

您可以将IHttpContextAccessor 实现注入(inject)到您的 View 中并使用它来获取 session 对象

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
<h1>@HttpContextAccessor.HttpContext.Session.GetString("userLoggedName")</h1>

假设您已经在 Startup 类中设置了启用 session 的所有设置。

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?}");

    });
}

关于c# - 在 Asp Core 2 View 中访问 Session 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46877349/

相关文章:

c# - 在c#中添加数字

c# - 如何创建一个名为 "checked"的属性?

c# - 我可以从 ActionResult 中检索 ViewModel 吗?

c# - 如何从 Request.Form 获取所有元素值而不用 .GetValues ("ElementIdName"准确指定哪个元素值)

razor - 无法让 FontAwesome 在 Razor 中工作

javascript - 根据从 DropDownList 中选择的项目显示 ViewBag 的属性并发布 ID

c# - 最快的基于字典的类实现是什么?

c# - WinForm 中的日期时间选择器 如何选择时间?

c# - 如何将 const int 从托管 C++ DLL 传递到 C# 以用作属性中的字段值

c# - Razor View 中的 Mvc5 VS2013 错误