3

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);
        }
    }
}
4
  • Simply assign Session["cart"] = jsoncart; will work because it comes from Controller class. The System.Web.HttpContext.Current instance may having no context at the time you're using it. Commented Aug 2, 2018 at 5:30
  • 1
    Possible duplicate of What is a NullReferenceException, and how do I fix it? Commented Aug 2, 2018 at 5:31
  • @TetsuyaYamamoto if I use Session["cart"] = jsoncart; I will get The name 'Session' does not exists in the current context Commented Aug 2, 2018 at 5:35
  • 2
    Sorry, I'm forgot you're using Core MVC. The Session usage is slightly different because System.Web namespace not exist (see this reference): HttpContext.Session.SetString("cart", jsoncart);. Commented Aug 2, 2018 at 5:41

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

I got the exact same error when I was working .NET Framework Web APIs, You can try if this works for you MVC project.

Make sure you have this in you Web.config

<system.web>
    <sessionState mode="InProc" timeout="20" />
</system.web>

You then need to enable session state for Web API. Add this to your Global.asax.cs

 protected void Application_PostAuthorizeRequest()
 {
     if (IsWebApiRequest())
     {
         HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
     }
 }

 private bool IsWebApiRequest()
 {
     return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith("~/api");
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.