System.Web.HttpContext.Current.get returned null in asp.net mvc controller
13,874
The System.Web namespace is not used in ASP.NET Core MVC, hence System.Web.HttpContext.Current property will always return null value (note that HttpContext is injected). If you want to set session variable in IActionResult controller, you can use SessionExtensions.SetString method:
string key = "cart";
HttpContext.Session.SetString(key, jsoncart);
If you want to retrieve it, use SessionExtensions.GetString method:
string jsonCart = HttpContext.Session.GetString("cart");
Note: To get HttpContext instance work, put using Microsoft.AspNetCore.Http; before namespace declaration.
Further reference: Session and app state in ASP.NET Core
Author by
Ng Hong Han
Updated on November 22, 2022Comments
-
Ng Hong Han 6 months
I want to use Session in an action of my MVC controller but I encountered this error but I'm not sure why the error is coming out.
System.NullReferenceException: 'Object reference not set to an instance of an object.' System.Web.HttpContext.Current.get returned null.Controller:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using fyp.Models; using System.Security.Claims; using System.Data; using System.Web; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; namespace fyp.Controllers { public class CustomerController : Controller { //Omitted actions [HttpGet] public IActionResult StartOrderMenu() { ViewData["Layout"] = "_Layout"; List<Cart> carts = new List<Cart>(); var jsoncart = JsonConvert.SerializeObject(carts); System.Web.HttpContext.Current.Session["cart"] = jsoncart; DbSet<Food> dbs = _dbContext.Food; List<Food> model = dbs.ToList(); return View(model); } } }-
Tetsuya Yamamoto almost 5 yearsSimply assignSession["cart"] = jsoncart;will work because it comes fromControllerclass. TheSystem.Web.HttpContext.Currentinstance may having no context at the time you're using it. -
Divyang Desai almost 5 yearsPossible duplicate of What is a NullReferenceException, and how do I fix it? -
Ng Hong Han almost 5 years@TetsuyaYamamoto if I use
Session["cart"] = jsoncart;I will getThe name 'Session' does not exists in the current context -
Tetsuya Yamamoto almost 5 yearsSorry, I'm forgot you're using Core MVC. TheSessionusage is slightly different becauseSystem.Webnamespace not exist (see this reference):HttpContext.Session.SetString("cart", jsoncart);.
-