System.Web.HttpContext.Current.get在ASP.NET MVC控制器中返回null

洪汉

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

System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Web.HttpContext.Current.get returned null.

控制器:

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);
        }
    }
}
山本哲也

System.Web命名空间是不是在ASP.NET MVC的核心使用,因此System.Web.HttpContext.Current属性将始终返回空值(注意,HttpContext注入)。如果要在IActionResult控制器中设置会话变量,可以使用以下SessionExtensions.SetString方法:

string key = "cart";

HttpContext.Session.SetString(key, jsoncart);

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

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

注意:要获得HttpContext实例工作,请using Microsoft.AspNetCore.Http;在名称空间声明之前放置

进一步参考:ASP.NET Core中的会话和应用程序状态

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

ASP.Net MVC控制器构造函数显示错误System.Web.Mvc.Controller.Session.get返回null

COM可见.NET类在经典ASP中使用时无法获取System.Web.HttpContext.Current

ASP.NET Web Api中HttpContext.Current.Items的替代方法

在ASP.NET 5中为Web API控制器模拟HttpContext

在ASP.NET Core3.1中使用包含'System.Web.HttpContext'的旧项目

ASP.NET 4.6异步控制器方法在等待后丢失HttpContext.Current

Ninject.MVC3-NinjectWebCommon RegisterServices System.Web.HttpContext.Current为null

在ASP.NET Core中HttpContext.Current.Features.Get <IRequestCultureFeature>()为空

如何在ASP.NET MVC / Web控制器中返回JSON?

将 ASP.NET MVC HttpContext 发送到 Web Api HttpContext

System.Web.HttpContext.Current不存在

System.Web.HttpContext.Current在异步中线程安全吗?

Visual Studio无法识别HttpContext.Current [ASP.NET MVC]

如何在ASP.NET Core 1.1中对使用HttpContext的MVC控制器进行单元测试

.Net标准的自定义System.Web.HttpContext

Asp.Net Core 2.0中Httpcontext.Current.Request.Files的替代方法是什么?

如何在ASP.NET Core中获取HttpContext.Current?

ASP.NET Core 2中HttpContext.Current.Items.Contains(DataContextKey)的替代方法

ASP.NET CORE版本中的HttpContext.Current.Request.Form.AllKeys

Task.Run内部的ASP.NET HttpContext.Current

ASP.NET Core 3.0 HttpContext.Current.Server.MapPath

ASP.NET MVC 6中的MVC控制器和Web API控制器有什么区别?

从ASP.net MVC 4 WEB API控制器返回byte []

从ASP.NET Web API中的控制器返回二进制文件

Post方法在Asp.net核心Web API控制器中返回404

Asp.Net MVC中Web API的默认控制器操作

多次等待后,控制器中的HTTPContext.Current为null

忽略ASP.NET Web API中的控制器

ASP.NET Web API中具有多个GET方法的单个控制器