1

I've added app.UseSession(); to my startup.Configure and services.AddSession() to my ConfigureServices.

Now if I try to use Session like this:

HttpContext.Session.SetString("Type", tableName);

I get "an object reference is required for the non-static field, method or property, 'HttpContext.Session'"

However, if I try to instantiate it like this: HttpContext context = new HttpContext();

it says: "Cannot create an instance of the abstract class or interface 'HttpContext"

How can I access session?

IQuery.cs

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace AppName.Services
{
    public interface IQuery
    {
        List<Dictionary<string, string>> GetListOfDatabases(string dbName);
    }
    public class InMemoryIquery : IQuery
    {
        public List<Dictionary<string, string>> GetListOfDatabases(string tableName)
        {
        if(tableName != null)
            {
               HttpContext.Session.SetString("Type", tableName);
            }
        }
    }
NickyLarson
  • 115
  • 1
  • 2
  • 18

2 Answers2

4

In your class add the IHttpContextAccessor to your constructor and use like this

public class InMemoryIquery : IQuery
{
    private IHttpContextAccessor _httpContextAccessor;

    public InMemoryIquerty(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public List<Dictionary<string, string>> GetListOfDatabases(string tableName)
    {
    if(tableName != null)
        {
           _httpContextAccessor.HttpContext.Session.SetString("CalculationType", tableName);
        }
    }
}

In your ConfigureServices add the following line services.AddHttpContextAccessor(); after services.AddControllersWithViews();

Andre.Santarosa
  • 1,150
  • 1
  • 9
  • 22
0

In the outside of this class, Use this to get current HttpContext.

HttpContext context = HttpContext.Current;

Then inject it into the constructor of this class. you must have something like this:

public InMemoryIquery(HttpContext httpContext)
{
   httpContext.Session.SetString("CalculationType", tableName);
}
Milad Dastan Zand
  • 1,062
  • 1
  • 10
  • 21