1

I'm attempting to use session variables in my Razor Pages application. I installed the NuGet package "Microsoft.AspNetCore.Session". Here is my Startup.cs file:

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

This is my function:

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

    }

And I call it like this:

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

The error I get for Session.GetString() is:

NullReferenceException: Object reference not set to an instance of an object.

I assume it has to do with HttpContext, but I thought that was instantiated with app.UseSession(). Anyone have any suggestions?

user301340
  • 60
  • 1
  • 9
  • Duplicate https://stackoverflow.com/questions/31243068/access-the-current-httpcontext-in-asp-net-core – Hameed Syed Jan 26 '18 at 03:53
  • I don't believe this is a duplicate because the implementation has changed since 2015 with the release of .Net Core 2.0 – user301340 Jan 26 '18 at 03:59

3 Answers3

0

I will tell you what I do in an ASP.NET Core 2 project. Make sure that the following nuget package is installed in your application:

Microsoft.AspNetCore.Session

Add the following lines in the ConfigureServices of the Startup.cs file:

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

Add the following lines of code in the Configure of the Startup.cs file:

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

Now you can access the session values from a controller like this:

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

in your view you can do the following:

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

In both cases you have to check if the specified key has a value.

I hope it helps.

pitaridis
  • 2,801
  • 3
  • 22
  • 41
  • Thanks for the response. I couldn't get the inject working but that led me to finding the HttpHelper class that I posted. Thanks! – user301340 Jan 27 '18 at 04:05
0

I got it working. I ended up defining this class:

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

    public static HttpContext HttpContext => _accessor.HttpContext;
}

I added these lines to my Startup.cs

Configure Services:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

In Configure I added:

HttpHelper.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());

and when I call it, I use this:

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

Its pretty involved just to get this basic functionality working.

user301340
  • 60
  • 1
  • 9
0
    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");


    }
abd.agha
  • 209
  • 2
  • 2