title: How to use session variables in ASP.NET Core 3.1 MVC using C#
body: <p>I'm having trouble with session objects. To set and get inside the same controller will work fine, my trouble is to use the info saved in the session in another controller, it doesn't work for me, every time I get a null value. I used to code PHP, I just needed to start session and get the values. No idea how to do it in ASP.NET Core 3.1 MVC.</p>
  <pre><code>using Microsoft.AspNetCore.Http;
  using Microsoft.AspNetCore.Mvc;
  using partner2.Data;
  using partner2.Helpers;
  using partner2.Models;
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;
  
  namespace partner2.Controllers
  {
      public class UsuarioController : Controller
      {
          public IActionResult Index()
          {
              return View();
          }
  
          public IActionResult Create()
          {
              return View();
          }
  
          [HttpPost]
          [ValidateAntiForgeryToken]//antiataque
          public IActionResult Create(Usuario usuario)
          {
              Sql sql = new Sql();
  
              usuario.id_ativo = true;
              usuario.senha = GenerateMD5.CreateMD5(usuario.senha);
              sql.addUser(usuario);
              int userid = sql.getIdByCpf(usuario.cpf);
              HttpContext.Session.SetInt32(&quot;userid&quot;, userid);
  
              if (!sql.enderecoExists(usuario.cpf))
              {
                  return View(&quot;CreateAdress&quot;);
              }
  
              return View();
          }
  
          public IActionResult CreateAdress(Endereco endereco)
          {
              Sql sql = new Sql();
              int? id = HttpContext.Session.GetInt32(&quot;userid&quot;);
  
              sql.addEndereco(endereco);
  
              return View();
          }
      }
  }
  </code></pre>