Soner
Soner

Reputation: 1282

How to use session and call from class asp.net mvc 6

I am trying to use session in asp.net mvc 6 from calling class inside of Iactionresult.

I have class as "SessionTool as below"

SessionTool class:

public class SessionTool
{
        private readonly IHttpContextAccessor HttpContextAccessor;

        public SessionTool(IHttpContextAccessor httpContextAccessor)
        {
            HttpContextAccessor = httpContextAccessor;
        }

        public void SetSession(string key, string value)
        {
            HttpContextAccessor.HttpContext.Session.SetString(key, value);
        }

        public string GetSession(string key)
        {
            return HttpContextAccessor.HttpContext.Session.GetString(key);
        }
 }

I have HomeController as below.

public class HomeController : Controller
{

        [HttpGet]
        public IActionResult Login() 
        {


        SessionTool sessionTool = new SessionTool(IHttpContextAccessor);


        }
}

Question:

If i try to call SessionTools class as below IHttpContextAccessor displays warning as IHttpContextAccessor is a type , which is not valid in the given context.

SessionTool sessionTool = new SessionTool(IHttpContextAccessor);

I am new in asp.net mvc 6 and i am not sure how can i set new instance of IHttpContextAccessor to session tool than use session classes ?

Any help will be appreciated. Thanks

Upvotes: 0

Views: 1435

Answers (1)

ahmet
ahmet

Reputation: 734

I use static class for my session helper class. On that helper class I have static properties which return data from session with specific key. Here is an example of my session structure.

  public static class TaskManSession
{
    public static int SelectedProjectId
    {
        get
        {
           if (System.Web.HttpContext.Current.Session["ProjectId"] ==null)
               {
                 return 0;
               }
            return Convert.ToInt32(System.Web.HttpContext.Current.Session["ProjectId"]);
        }
        set
        {
            System.Web.HttpContext.Current.Session["ProjectId"] = value;
        }
    }
}

People don't prefer using static classes, because it is hard to use TDD (Test driven development) with static classes. You can read more from here

However "System.Web.HttpContext.Current.Session" class also has no instance. Therefore I don't see any problem to use a static helper.

Upvotes: 1

Related Questions