(ASP.NET Core Razor Pages) Unable to access Session Variables from other pages





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







2















I am trying to access some Session Variables in a Razor Pages application, but am met with NullReferenceException errors.



Currently, I set the variables in a method in the model associated with a "user login" page:



public void StoreUserData(string username, string name, int accesslevel)
{
HttpContext.Session.SetString("username", username);
HttpContext.Session.SetString("name", name);
HttpContext.Session.SetInt32("accesslevel", accesslevel);
}


I then call this method (and the method which gets the data to be stored) when the user submits the login form on the page (on post):



public IActionResult OnPost()
{
(string username, string name, int accesslevel) = Login();
StoreUserData(username, name, accesslevel);
ViewData["username"] = HttpContext.Session.GetString("username");
return Page();
}


I know that the session variables are being saved, and can be accessed (at least on the "login" page) because the "username" string is correctly displayed on the page using ViewData, as shown in the block above.



When I try to access the same session variables in another razor page, it doesn't work.



I want to check the session variables when the page loads. C# method (part of page model for second page):



public (string username, string name, int accesslevel) GetUserData()
{
string username = HttpContext.Session.GetString("username");
string name = HttpContext.Session.GetString("name");
int accesslevel = Convert.ToInt32(HttpContext.Session.GetInt32("accesslevel"));

return (username, name, accesslevel);
}


And C# block on html page to call this method (I don't know a better way to do this when the page loads):



@{ 
Test_1Model model = new Test_1Model();
(string username, string name, int accesslevel) = model.GetUserData();
<div>@username</div>
}


At the moment, I just want to display one of the session variables on this second page to check everything's working.



Finally, in startup.cs:
Configure Services:



public void ConfigureServices(IServiceCollection services)
{
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
});

services.AddHttpContextAccessor();

services.AddMemoryCache();

services.AddMvc();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}


Configure:



public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});


I know it's a lot of information, but I've tried to be as thorough as possible. Any help is greatly appreciated.










share|improve this question





























    2















    I am trying to access some Session Variables in a Razor Pages application, but am met with NullReferenceException errors.



    Currently, I set the variables in a method in the model associated with a "user login" page:



    public void StoreUserData(string username, string name, int accesslevel)
    {
    HttpContext.Session.SetString("username", username);
    HttpContext.Session.SetString("name", name);
    HttpContext.Session.SetInt32("accesslevel", accesslevel);
    }


    I then call this method (and the method which gets the data to be stored) when the user submits the login form on the page (on post):



    public IActionResult OnPost()
    {
    (string username, string name, int accesslevel) = Login();
    StoreUserData(username, name, accesslevel);
    ViewData["username"] = HttpContext.Session.GetString("username");
    return Page();
    }


    I know that the session variables are being saved, and can be accessed (at least on the "login" page) because the "username" string is correctly displayed on the page using ViewData, as shown in the block above.



    When I try to access the same session variables in another razor page, it doesn't work.



    I want to check the session variables when the page loads. C# method (part of page model for second page):



    public (string username, string name, int accesslevel) GetUserData()
    {
    string username = HttpContext.Session.GetString("username");
    string name = HttpContext.Session.GetString("name");
    int accesslevel = Convert.ToInt32(HttpContext.Session.GetInt32("accesslevel"));

    return (username, name, accesslevel);
    }


    And C# block on html page to call this method (I don't know a better way to do this when the page loads):



    @{ 
    Test_1Model model = new Test_1Model();
    (string username, string name, int accesslevel) = model.GetUserData();
    <div>@username</div>
    }


    At the moment, I just want to display one of the session variables on this second page to check everything's working.



    Finally, in startup.cs:
    Configure Services:



    public void ConfigureServices(IServiceCollection services)
    {
    services.AddSession(options =>
    {
    options.IdleTimeout = TimeSpan.FromMinutes(10);
    });

    services.AddHttpContextAccessor();

    services.AddMemoryCache();

    services.AddMvc();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }


    Configure:



    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    app.UseStaticFiles();
    app.UseSession();
    app.UseMvc(routes =>
    {
    routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");
    });


    I know it's a lot of information, but I've tried to be as thorough as possible. Any help is greatly appreciated.










    share|improve this question

























      2












      2








      2








      I am trying to access some Session Variables in a Razor Pages application, but am met with NullReferenceException errors.



      Currently, I set the variables in a method in the model associated with a "user login" page:



      public void StoreUserData(string username, string name, int accesslevel)
      {
      HttpContext.Session.SetString("username", username);
      HttpContext.Session.SetString("name", name);
      HttpContext.Session.SetInt32("accesslevel", accesslevel);
      }


      I then call this method (and the method which gets the data to be stored) when the user submits the login form on the page (on post):



      public IActionResult OnPost()
      {
      (string username, string name, int accesslevel) = Login();
      StoreUserData(username, name, accesslevel);
      ViewData["username"] = HttpContext.Session.GetString("username");
      return Page();
      }


      I know that the session variables are being saved, and can be accessed (at least on the "login" page) because the "username" string is correctly displayed on the page using ViewData, as shown in the block above.



      When I try to access the same session variables in another razor page, it doesn't work.



      I want to check the session variables when the page loads. C# method (part of page model for second page):



      public (string username, string name, int accesslevel) GetUserData()
      {
      string username = HttpContext.Session.GetString("username");
      string name = HttpContext.Session.GetString("name");
      int accesslevel = Convert.ToInt32(HttpContext.Session.GetInt32("accesslevel"));

      return (username, name, accesslevel);
      }


      And C# block on html page to call this method (I don't know a better way to do this when the page loads):



      @{ 
      Test_1Model model = new Test_1Model();
      (string username, string name, int accesslevel) = model.GetUserData();
      <div>@username</div>
      }


      At the moment, I just want to display one of the session variables on this second page to check everything's working.



      Finally, in startup.cs:
      Configure Services:



      public void ConfigureServices(IServiceCollection services)
      {
      services.AddSession(options =>
      {
      options.IdleTimeout = TimeSpan.FromMinutes(10);
      });

      services.AddHttpContextAccessor();

      services.AddMemoryCache();

      services.AddMvc();
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
      }


      Configure:



      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
      app.UseStaticFiles();
      app.UseSession();
      app.UseMvc(routes =>
      {
      routes.MapRoute(
      name: "default",
      template: "{controller=Home}/{action=Index}/{id?}");
      });


      I know it's a lot of information, but I've tried to be as thorough as possible. Any help is greatly appreciated.










      share|improve this question














      I am trying to access some Session Variables in a Razor Pages application, but am met with NullReferenceException errors.



      Currently, I set the variables in a method in the model associated with a "user login" page:



      public void StoreUserData(string username, string name, int accesslevel)
      {
      HttpContext.Session.SetString("username", username);
      HttpContext.Session.SetString("name", name);
      HttpContext.Session.SetInt32("accesslevel", accesslevel);
      }


      I then call this method (and the method which gets the data to be stored) when the user submits the login form on the page (on post):



      public IActionResult OnPost()
      {
      (string username, string name, int accesslevel) = Login();
      StoreUserData(username, name, accesslevel);
      ViewData["username"] = HttpContext.Session.GetString("username");
      return Page();
      }


      I know that the session variables are being saved, and can be accessed (at least on the "login" page) because the "username" string is correctly displayed on the page using ViewData, as shown in the block above.



      When I try to access the same session variables in another razor page, it doesn't work.



      I want to check the session variables when the page loads. C# method (part of page model for second page):



      public (string username, string name, int accesslevel) GetUserData()
      {
      string username = HttpContext.Session.GetString("username");
      string name = HttpContext.Session.GetString("name");
      int accesslevel = Convert.ToInt32(HttpContext.Session.GetInt32("accesslevel"));

      return (username, name, accesslevel);
      }


      And C# block on html page to call this method (I don't know a better way to do this when the page loads):



      @{ 
      Test_1Model model = new Test_1Model();
      (string username, string name, int accesslevel) = model.GetUserData();
      <div>@username</div>
      }


      At the moment, I just want to display one of the session variables on this second page to check everything's working.



      Finally, in startup.cs:
      Configure Services:



      public void ConfigureServices(IServiceCollection services)
      {
      services.AddSession(options =>
      {
      options.IdleTimeout = TimeSpan.FromMinutes(10);
      });

      services.AddHttpContextAccessor();

      services.AddMemoryCache();

      services.AddMvc();
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
      }


      Configure:



      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
      app.UseStaticFiles();
      app.UseSession();
      app.UseMvc(routes =>
      {
      routes.MapRoute(
      name: "default",
      template: "{controller=Home}/{action=Index}/{id?}");
      });


      I know it's a lot of information, but I've tried to be as thorough as possible. Any help is greatly appreciated.







      asp.net-core session-variables nullreferenceexception razor-pages session-storage






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 16:07









      bbbbbbbb

      696




      696
























          1 Answer
          1






          active

          oldest

          votes


















          1














          This is caused by that Test_1Model model = new Test_1Model();, you should use Model instead of initializing a new Test_1Model. For this new object, it is not related with your request, it's just an object.



          Try.



          @{
          ViewData["Title"] = "Contact";
          //ContactModel model = new ContactModel();
          (string username, string name, int accesslevel) = Model.GetUserData();
          <div>@username</div>
          }





          share|improve this answer
























          • It works! Thank you very much

            – bbbb
            Nov 23 '18 at 8:24












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53434734%2fasp-net-core-razor-pages-unable-to-access-session-variables-from-other-pages%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          This is caused by that Test_1Model model = new Test_1Model();, you should use Model instead of initializing a new Test_1Model. For this new object, it is not related with your request, it's just an object.



          Try.



          @{
          ViewData["Title"] = "Contact";
          //ContactModel model = new ContactModel();
          (string username, string name, int accesslevel) = Model.GetUserData();
          <div>@username</div>
          }





          share|improve this answer
























          • It works! Thank you very much

            – bbbb
            Nov 23 '18 at 8:24
















          1














          This is caused by that Test_1Model model = new Test_1Model();, you should use Model instead of initializing a new Test_1Model. For this new object, it is not related with your request, it's just an object.



          Try.



          @{
          ViewData["Title"] = "Contact";
          //ContactModel model = new ContactModel();
          (string username, string name, int accesslevel) = Model.GetUserData();
          <div>@username</div>
          }





          share|improve this answer
























          • It works! Thank you very much

            – bbbb
            Nov 23 '18 at 8:24














          1












          1








          1







          This is caused by that Test_1Model model = new Test_1Model();, you should use Model instead of initializing a new Test_1Model. For this new object, it is not related with your request, it's just an object.



          Try.



          @{
          ViewData["Title"] = "Contact";
          //ContactModel model = new ContactModel();
          (string username, string name, int accesslevel) = Model.GetUserData();
          <div>@username</div>
          }





          share|improve this answer













          This is caused by that Test_1Model model = new Test_1Model();, you should use Model instead of initializing a new Test_1Model. For this new object, it is not related with your request, it's just an object.



          Try.



          @{
          ViewData["Title"] = "Contact";
          //ContactModel model = new ContactModel();
          (string username, string name, int accesslevel) = Model.GetUserData();
          <div>@username</div>
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 '18 at 7:12









          Tao ZhouTao Zhou

          7,61231434




          7,61231434













          • It works! Thank you very much

            – bbbb
            Nov 23 '18 at 8:24



















          • It works! Thank you very much

            – bbbb
            Nov 23 '18 at 8:24

















          It works! Thank you very much

          – bbbb
          Nov 23 '18 at 8:24





          It works! Thank you very much

          – bbbb
          Nov 23 '18 at 8:24




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53434734%2fasp-net-core-razor-pages-unable-to-access-session-variables-from-other-pages%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          mysqli_query(): Empty query in /home/lucindabrummitt/public_html/blog/wp-includes/wp-db.php on line 1924

          How to change which sound is reproduced for terminal bell?

          Can I use Tabulator js library in my java Spring + Thymeleaf project?