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); } } } 
8
  • In what context are you accessing it? See Access HttpContext in ASP.NET Core Commented Feb 21, 2020 at 11:08
  • I am trying to access it from within a class that inherits an interface Commented Feb 21, 2020 at 11:11
  • Can you post the full code where you are trying to access the Session? Commented Feb 21, 2020 at 11:12
  • We can help, if you send the full code of that class that accesses the session. Commented Feb 21, 2020 at 11:15
  • I've posted the code above. Thanks Commented Feb 21, 2020 at 11:20

2 Answers 2

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();

Sign up to request clarification or add additional context in comments.

Comments

-1

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

2 Comments

This is not correct in .Net Core, or possibly anywhere. You should use the HttpContextAccessor
oh you right in.net core, see this stackoverflow.com/questions/31243068/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.