.Net Session Variables NullReferenceException



我正在尝试在我的 Razor 页面应用程序中使用会话变量。我安装了NuGet包"Microsoft.AspNetCore.Session"。这是我的启动.cs文件:

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Adds a default in-memory implementation of IDistributedCache.
        services.AddDistributedMemoryCache();
        services.AddSession();
        services.AddMvc();
    }
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Error");
        }
        app.UseSession();
        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });
    }

这是我的函数:

    public string GetText()
    {
        if (HttpContext.Session.GetString("_MessageText") != null)
        {
            return HttpContext.Session.GetString("_MessageText");
        }
        else
        {
            return "You found an easter egg.";
        }
    }

我这样称呼它:

                <div class="col align-self-center">
                    @Message.GetText()
                </div>

我为 Session.GetString(( 得到的错误是:

NullReferenceException:对象引用未设置为实例 对象。

我认为它与HttpContext有关,但我认为这是用应用程序实例化的。使用会话((。有人有什么建议吗?

我会告诉你我在 ASP.NET Core 2项目中做了什么。请确保在应用程序中安装了以下 nuget 包:

Microsoft.AspNetCore.Session

在 Startup.cs 的 ConfigureServices 文件中添加以下行:

public void ConfigureServices(IServiceCollection services)  
{
    services.AddMvc()
        .AddSessionStateTempDataProvider();                 <=== For asp.net core 2
    services.AddDistributedMemoryCache();                   <===
    services.AddSession(options =>                          <===
    {                                                       <===
        options.IdleTimeout = TimeSpan.FromMinutes(30);     <===
        options.CookieName = ".MyApplication";              <===
    });                                                     <===
}

在"启动.cs的配置"文件中添加以下代码行:

public void Configure(IApplicationBuilder app)  
{
    app.UseStaticFiles();
    //enable session before MVC
    app.UseSession();                       <===
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

现在,您可以从控制器访问会话值,如下所示:

string value = HttpContext.Session.GetString("value");

在您的视图中,您可以执行以下操作:

@using Microsoft.AspNetCore.Http
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@{
    string value = HttpContextAccessor.HttpContext.Session.GetString("value");
}

在这两种情况下,您都必须检查指定的键是否具有值。

我希望它有所帮助。

我让它工作了。我最终定义了这个类:

public static class HttpHelper
{
        private static IHttpContextAccessor _accessor;
        public static void Configure(IHttpContextAccessor httpContextAccessor)
        {
            _accessor = httpContextAccessor;
        }
    public static HttpContext HttpContext => _accessor.HttpContext;
}

我将这些行添加到我的启动中.cs

配置服务:

服务业。AddSingleton<IHttpContextAccessor,>((;

在"配置"中,我添加了:

HttpHelper.Configure(app.ApplicationServices.GetRequiredService(((;

当我调用它时,我使用这个:

title = HttpHelper.HttpContext.Session.GetString("_MessageTitle"(;

它非常复杂,只是为了让这个基本功能正常工作。

    public string _User_Id;
    public void ge_tUserIdFromSessions()
    {
        //in a controller you can use :         
        //_User_Id = HttpContext.Session.GetString("UserId");
        //but in a class U can use:
        var httpContextAccessor = new HttpContextAccessor();
        _User_Id = httpContextAccessor.HttpContext.Session.GetString("UserId");

    }

最新更新