asp.net mvc的不能在基本控制器访问Cookie数据 [英] asp.net mvc can't access cookie data in base controller
问题描述
有关要求的每一页,我需要检查一个cookie或创建它,如果它不存在。
如果cookie是存在的,我需要加载从DB一些信息基于cookie的内容。
For every page requested, I need to check a cookie or create it if it's not there. If the cookie is there, I need to load up some info from the DB based on the contents of that cookie.
要做到这一点我创建了一个叫做AppController的,我的其他控制器继承基控制器。
To do this I have created a base controller called AppController that my other controllers inherit from.
然后我有这样的事(这样CurrentSessionValues对象是提供给我的所有控制器):
then I have something like this (so that the CurrentSessionValues object is available to all my controllers):
public MySession CurrentSessionValues;
public ApplicationController()
{
if (Request.Cookies["MySiteCookie"] == null)
{
// create new Record in DB
CurrentSessionValues = CreateMySession();
HttpCookie cookie = new HttpCookie("MySiteCookie");
cookie.Value = CurrentSessionValues.SessionID.ToString;
Response.SetCookie(cookie);
}
else
{
// use the value in MySiteCookie to get values from the DB
// e.g. logged in user id, cart id, etc
}
}
当我运行它,我得到Default.aspx中这个错误:
When I run this, I get this error in default.aspx:
在创建时出现错误
型控制器
Mvc_Learn.Controllers.HomeController。
An error occurred while creating a controller of type 'Mvc_Learn.Controllers.HomeController'.
如果控制器不具有
控制器工厂,保证其具有
无参数的公共构造函数。
If the controller doesn't have a controller factory, ensure that it has a parameterless public constructor.
它打破了对Request.Cookies时[MySiteCookie]
It breaks on Request.Cookies["MySiteCookie"]
我应该以某种方式或其他地方做这个逻辑?
Should I be doing this logic in some other way or another place?
推荐答案
技巧是,你不必在构造背景下必然。相反,你应该重写初始化方法:
Trick is that you don't have context in the constructor necessarily. Rather, you should override the Initialize method:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
//check request context for cookie and do your thang.
}
PS:为子孙后代,我要指出为什么会出现错误。异常信息的关键部分是发生了一个错误,同时创造控制器,参数构造位在这种情况下,一个红色的鲱鱼。而发生的错误是一个空引用例外HttpContext的。
PS: for posterity, I should note why there is an error. The key part of the exception info is that an error took place while creating the controller, the parameterless constructor bit is a red herring in this case. The error which took place was a null reference exception to HttpContext.
这篇关于asp.net mvc的不能在基本控制器访问Cookie数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!