我正在使用ASP.Net Core 2.1.1。在控制器中调用 HttpContext 时遇到问题。当我想使用 HttpContext 时,程序返回 NullReferenceException 并说 HttpContext.get 返回null。
我很困惑,因为它在控制器内部。您能帮我找出可能的原因吗?
CartController .cs
public class CartController : Controller
{
private readonly IProductServices _productServices;
private readonly ICartServices _cartServices;
public CartController(IProductServices productServices, ICartServices cartServices)
{
_productServices = productServices;
_cartServices = cartServices;
cartServices.Cart = GetCart();
}
public RedirectToActionResult AddToCart(int productID, string returnUrl)
{
ProductViewModel product = _productServices.GetByID(productID);
if (product != null)
{
_cartServices.AddItem(product, 1);
SaveCart(_cartServices.Cart);
}
return RedirectToAction("Index", new { returnUrl });
}
public RedirectToActionResult RemoveFromCart(int productID, string returnUrl)
{
ProductViewModel product = _productServices.GetByID(productID);
if (product != null)
{
_cartServices.RemoveLine(product);
SaveCart(_cartServices.Cart);
}
return RedirectToAction("Index", new { returnUrl });
}
public IActionResult Index(string returnUrl)
{
return View(new CartIndexViewModel()
{
Cart = GetCart(),
ReturnUrl = returnUrl
});
}
private CartViewModel GetCart()
{
return HttpContext.Session.GetJson<CartViewModel>("Cart") ?? new CartViewModel();
}
private void SaveCart(CartViewModel cart)
{
HttpContext.Session.SetJson<CartViewModel>("Cart", cart);
}
}
此行调用:Cart = GetCart()
时,它返回null。
Startup.cs
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSession();
services.AddMemoryCache();
services.AddMvc();
services.RegisterStartupServices(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: null,
template: "{category}/Page{page:int}",
defaults: new { controller = "Product", action = "List" }
);
routes.MapRoute(
name: null,
template: "Page{page:int}",
defaults: new { controller = "Product", action = "List", page = 1 }
);
routes.MapRoute(
name: null,
template: "{category}",
defaults: new { controller = "Product", action = "List", page = 1 }
);
routes.MapRoute(
name: null,
template: "",
defaults: new { controller = "Product", action = "List", page = 1 }
);
routes.MapRoute(
name: "default",
template: "{controller=Product}/{action=List}/{id?}"
);
});
}
}
我在另一个程序集中编写了应用程序依赖项注入代码,并从 Sturtup.cs
进行了调用StartupExtensions.cs
public static class StartupExtensions
{
public static void RegisterStartupServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<SportStoreDbContext>(x => x.UseSqlServer(configuration.GetConnectionString("SportStoreDatabase")));
MapperConfiguration mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddTransient<IProductServices, ProductServices>();
services.AddTransient<ICategoryServices, CategoryServices>();
services.AddTransient<ICartServices, CartServices>();
}
}
谢谢
答案 0 :(得分:1)
您在构造函数中调用方法GetCart
:
public CartController(IProductServices productServices, ICartServices cartServices)
{
_productServices = productServices;
_cartServices = cartServices;
cartServices.Cart = GetCart();
}`
...
private CartViewModel GetCart()
{
return HttpContext.Session.GetJson<CartViewModel>("Cart") ?? new CartViewModel();
}
,但是HttpContext属性尚未初始化。您只能在处理请求时拥有Http上下文。