aspnet-sessionId not working for Asp.Net Core
05:57 03 Dec 2018

I am migrating an ASP.Net application to ASP.Net Core. Principally setting up NLog works fine as expected. Now I want to log the session id together with the log message. For that I added - Microsoft.AspNetCore.Session - NLog.Web.AspNetCore from NuGet.

Sessions are activated in Startup and I get Session IDs in the code.

Following NLog on GitHub in the Startup.cs one should add

//add NLog.Web
app.AddNLogWeb();

which doesn't make any sense because the method is marked obsolete.

However, neither with that line nor without it NLog produces correct output to the logfile. Only the following is logged:

2018-12-03 09:59:42.6111 Warn Exception in layout renderer. Exception: System.InvalidOperationException: Session has not been configured for this application or request.
   at Microsoft.AspNetCore.Http.DefaultHttpContext.get_Session()
   at NLog.Web.LayoutRenderers.AspNetSessionIdLayoutRenderer.DoAppend(StringBuilder builder, LogEventInfo logEvent)
   at NLog.LayoutRenderers.LayoutRenderer.RenderAppendBuilder(LogEventInfo logEvent, StringBuilder builder)

The target configuration looks like this:

    

And here is the content of Startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(120);
            options.Cookie.HttpOnly = true;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // 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();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseSession();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

What is missing in my configuration?

c# asp.net asp.net-core nlog