c# - System.Web.HttpContext.Current.get 在 asp.net mvc Controller 中返回 null

标签 c# asp.net asp.net-mvc session asp.net-core-mvc

我想在 MVC Controller 的操作中使用 Session,但遇到此错误,但我不确定为什么会出现该错误。

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);
        }
    }
}

最佳答案

ASP.NET Core MVC 中不使用 System.Web 命名空间,因此 System.Web.HttpContext.Current 属性将始终返回 null 值(请注意 HttpContext 被注入(inject))。如果你想在IActionResult Controller 中设置 session 变量,你可以使用 SessionExtensions.SetString方法:

string key = "cart";

HttpContext.Session.SetString(key, jsoncart);

如果您想检索它,请使用 SessionExtensions.GetString方法:

string jsonCart = HttpContext.Session.GetString("cart");

注意:要使 HttpContext 实例正常工作,请将 using Microsoft.AspNetCore.Http; 放在命名空间声明之前。

进一步引用:Session and app state in ASP.NET Core

关于c# - System.Web.HttpContext.Current.get 在 asp.net mvc Controller 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51646084/

相关文章:

c# - 提高网站性能 - ASP.NET

c# - ASP.NET C# MVC : How do I live without ViewState?

asp.net - 使用Azure Data Studio从容器查看SQL Server

asp.net - 连接更改对代码的影响

asp.net - 在通用 http 处理程序中处理 session 超时

c# - .NET SMTP 客户端 - 客户端无权作为此发件人发送

c# - 使用单个复选框动态禁用一堆文本框

c# - 反序列化来自 firebase 的响应

c# - 模拟和 HttpContextBase.get_User()

c# - PetaPoco 能否填充一个包含多个 POCO 的 View 模型列表?