如何在视图中获取会话值asp.net核心

Nav*_*tor 6 asp.net-mvc session-variables

我想尝试像这样的会议

@HttpContext.Session.GetString("some");
Run Code Online (Sandbox Code Playgroud)

但我得到了

*

非静态字段需要对象引用......

*

有想法的人吗?

Shy*_*yju 14

您必须将IHttpContextAccessor实现注入视图并使用它.

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
Run Code Online (Sandbox Code Playgroud)

现在您可以访问该HttpContext属性然后Session

<p>
    @HttpContextAccessor.HttpContext.Session.GetInt32("MySessionKey")
</p>
Run Code Online (Sandbox Code Playgroud)

假设您已完成所有必要的设置以启用课程中的会话startup.

在你的ConfigureServices方法中,

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Run Code Online (Sandbox Code Playgroud)

IApplicationBuilder.UseSession方法中的Configure方法调用.

app.UseSession();
Run Code Online (Sandbox Code Playgroud)


yog*_*ing 6

首先通过在启动类的 ConfigureServices 方法中添加以下两行代码来启用会话:

services.AddMemoryCache();
services.AddSession();
Run Code Online (Sandbox Code Playgroud)

在相同的方法中添加用于为 IHttpContextAccessor 创建单例对象以访问视图中的会话的代码。

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Run Code Online (Sandbox Code Playgroud)

现在在启动类的 Configure 方法中,您必须在 .UseMvc() 之前添加 .UseSession() :

app.UseSession();
Run Code Online (Sandbox Code Playgroud)

Startup 类的完整代码如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddMemoryCache();
    services.AddSession();
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDeveloperExceptionPage();
    app.UseStatusCodePages();
    app.UseStaticFiles();
    app.UseSession();
    app.UseMvc(routes =>
    {
        // Default Route
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
Run Code Online (Sandbox Code Playgroud)

然后转到视图并在顶部添加以下两行:

@using Microsoft.AspNetCore.Http
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
Run Code Online (Sandbox Code Playgroud)

然后您可以从视图中的会话变量中获取值,例如:

@HttpContextAccessor.HttpContext.Session.GetString("some")
Run Code Online (Sandbox Code Playgroud)

我只是通过包含完整的代码修改了@Shyju 的答案。