Search code examples
c#asp.net-corerazor-pages

How can I access the HTTPContext in a class derived from PageModel?


In order to simplify the handling of the session variables in my Razor page, I would like to insert a separate class between the PageModel and the IndexModel.

PageModel <- MyPageModel <- IndexModel

Now I notice that in the classes MyPageModel and IndexModel the HTTPContext is defined but not set (=null). However, if I derive the class IndexModel directly from the class PageModel, everything is fine and I can access the HTTPContext and the session variables. The settings in Startup are fine so far, as the rest of the pages work fine. What am I doing wrong? Or have I overlooked something?

Class MyPageModel derived from PageModel

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WebApp.Areas.Ansicht12.Pages
{
    public class MyPageModel : PageModel
    {
        string s1 = default;
        string s2 = default;
        int i3 = 0;

        public MyPageModel() : base()
        {
            s1 = HttpContext.Session.GetString("Var-1");
            s2 = HttpContext.Session.GetString("Var-2");
            i3 = (int)HttpContext.Session.GetInt32("Var-3");
        }

    }
}`

Class IndexModel derived from MyPageModel

namespace WebApp.Areas.Ansicht12.Pages
{
    public class IndexModel : MyPageModel
    {
        public IndexModel() : base()
        {
        }

        public void OnGet()
        {
        }
    }
}

Solution

  • HttpContext is not available when the constructor of the Razor pages is called. You could use IHttpContextAccessor to meet your requirement.

    MyPageModel:

    public class MyPageModel : PageModel
    {
        string s1 = default;
        string s2 = default;
        int i3 = 0;
        public MyPageModel(IHttpContextAccessor httpContextAccessor) :base()    
        {
            s1 = httpContextAccessor.HttpContext.Session.GetString("Var-1");
            s2 = httpContextAccessor.HttpContext.Session.GetString("Var-2");
            i3 = (int)httpContextAccessor.HttpContext.Session.GetInt32("Var-3");
        }            
    }
    

    IndexModel :

    public class IndexModel: MyPageModel
    {
        public IndexModel(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
        {
        }
    
        public void OnGet()
        {
            
        }
    }
    

    Be sure register the service in Startup.ConfigureServices() method:

    services.AddHttpContextAccessor();