Maxim
Maxim

Reputation: 13468

Check for session in ASP.NET Core 1.0

Access to Session property of context raises exception because session is not configured.

How to detect if Session is available if it can be on or off depending on config.

In other words I cannot do this: context.Session?.Clear();

Upvotes: 2

Views: 3098

Answers (2)

DavidG
DavidG

Reputation: 119136

I think the safest and most performant way would be to use request features. For example, here's a simple extension method to get the session or null if it's not enabled:

public static ISession SafeSession(this HttpContext httpContext)
{
    var sessionFeature = httpContext.Features.Get<ISessionFeature>();
    return sessionFeature == null ? null : httpContext.Session;
}

Example usage from an MVC controller:

var session = this.HttpContext.SafeSession();

Upvotes: 6

Ignas
Ignas

Reputation: 4338

A hacky workaround, however might suffice to let you continue working until a better solution is found.

public class Startup
{
    public static bool IsSessionAvailable { get; set; }
    //...

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        IsSessionAvailable = false; // session not available

    //...

And then in your controller.

if (Startup.IsSessionAvailable)
{
    HttpContext.Session.Clear();
}

Upvotes: 0

Related Questions