Net 6 using session in a custom class

Jim Whitaker 21 Reputation points
2021-12-16T04:17:30.797+00:00

I can easily work with session in a page model like:

            string SessionKeyName = "logged";
            if (string.IsNullOrEmpty(HttpContext.Session.GetString(SessionKeyName)))
            {
                HttpContext.Session.SetString(SessionKeyName, "notlogged");
                //ViewData["mt"] = "notlogged";
                Response.Redirect("./login");
            }

But if I try to use session in a custom class I get an error:

Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field, method, or property 'HttpContext.Session' RazorPagesMovie C:\Users\Owner\source\repos\RazorPagesMovie\RazorPagesMovie\Helpers\Chk.cs 20 Active

How would I implement session in a custom class?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,239 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 57,886 Reputation points
    2021-12-17T17:33:46.683+00:00

    it would be simpler to just pass session to the class:

    using Microsoft.AspNetCore.Http;
     using Microsoft.AspNetCore.Mvc;
     using Microsoft.AspNetCore.Session;
    
    
     namespace RazorPagesMovie.Helpers
     {
         public class Chk
         {
             ISession session;
    
             public Chk(ISession session)
             {
                 this.session = session;
             }
    
             public void Foo()
             {
                 session?.SetString("Name", "Bobby");
                 session?.SetInt32("Age", 773);
             }
    
             public void getFoo()
             {
                 session?.GetString("Name");
                 session?.SetInt32("Age", 773);
             }
         }
     }
    

    in a page you create

    Chk chk = new Chk(HttpContext.Session);

    or create a session extension class

    public static class SessionExtensions
    {
         public static string? GetFoo (this ISession session) => return session["foo"];
         public static void SetFoo(this ISession session, string value) => session["foo"] = value; 
    }
    

    and use

    var foo = HttpContext.Session?.GetFoo();

    1 person found this answer helpful.
    0 comments No comments

9 additional answers

Sort by: Most helpful
  1. Jim Whitaker 21 Reputation points
    2021-12-16T22:07:10.607+00:00

    All I want to do is find out if a session key is set or not by returning true or false.

    But I want to do this from custom class where I can use anywhere, I even prefer a static method.

    Then I can do a if true do something, else do something else.

    I want to be able to call the custom class and function from any of the page models.

    Seems as though there would be an easy way.


  2. Jim Whitaker 21 Reputation points
    2021-12-17T03:45:37.657+00:00

    I will try it tomorrow, meanwhile I found an S.O. example, but can't call it. No errors in class:

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Session;
    
    
    namespace RazorPagesMovie.Helpers
    {
        public class Chk
        {
            IHttpContextAccessor accessor;
    
            public Chk(IHttpContextAccessor accessor)
            {
                this.accessor = accessor;
    
            }
    
            public void Foo()
            {
                var httpContext = accessor.HttpContext;
                httpContext?.Session.SetString("Name", "Bobby");
                //httpContext?.Session.SetInt32("Age", 773);
            }
    
            public void getFoo()
            {
                var httpContext = accessor.HttpContext;
                httpContext?.Session.GetString("Name");
                //httpContext?.Session.SetInt32("Age", 773);
            }
        }
    }
    

    But in page model where I have:

    Chk mychk = new Chk();
    

    It's expecting parameters, I have no idea what parameters to sent. The error is:

    Severity Code Description Project File Line Suppression State
    Error CS7036 There is no argument given that corresponds to the required formal parameter 'accessor' of 'Chk.Chk(IHttpContextAccessor)' RazorPagesMovie C:\Users\Owner\source\repos\RazorPagesMovie\RazorPagesMovie\Pages\pets\login.cshtml.cs 49 Active

    What parameters do I send?

    0 comments No comments

  3. Jim Whitaker 21 Reputation points
    2021-12-17T04:23:09.96+00:00

    Also tried the code, got:

    Severity Code Description Project File Line Suppression State
    Error CS0103 The name '_myclass' does not exist in the current context RazorPagesMovie C:\Users\Owner\source\repos\RazorPagesMovie\RazorPagesMovie\Pages\pets\index.cshtml.cs 42 Active

    So tried new keyword:

    MyClass myclass = new MyClass();
    
    //and
    string SessionKeyName = "logged";
    var result = myclass.getValue(SessionKeyName);
    

    But got another error:

    Severity Code Description Project File Line Suppression State
    Error CS1061 'MyClass' does not contain a definition for 'getValue' and no accessible extension method 'getValue' accepting a first argument of type 'MyClass' could be found (are you missing a using directive or an assembly reference?) RazorPagesMovie C:\Users\Owner\source\repos\RazorPagesMovie\RazorPagesMovie\Pages\pets\index.cshtml.cs 42 Active


  4. Jim Whitaker 21 Reputation points
    2021-12-17T18:09:22.247+00:00

    ZhiLv-MSFT, Bruce-SqlWork

    Closer, now only error is in this part:

            public DefaultModel(MyClass myClass, IHttpContextAccessor httpContextAccessor)
            {
                _myClass = myClass;
                _httpcontextAccessor = httpContextAccessor;
            }
    

    Error is:

    CS1520 Method must have a return type RazorPagesMovie C:\Users\Owner\source\repos\RazorPagesMovie\RazorPagesMovie\Pages\pets\index.cshtml.cs 23 Active

    Bruce-SqlWork I am looking over your code also.

    0 comments No comments