gpt4 book ai didi

asp.net-mvc - asp.net mvc 无法访问基本 Controller 中的 cookie 数据

转载 作者:行者123 更新时间:2023-12-04 23:10:47 25 4
gpt4 key购买 nike

对于请求的每个页面,我需要检查 cookie 或创建它,如果它不存在。
如果 cookie 在那里,我需要根据该 cookie 的内容从数据库加载一些信息。

为此,我创建了一个名为 AppController 的基本 Controller ,我的其他 Controller 继承自该 Controller 。

然后我有这样的东西(以便 CurrentSessionValues 对象可用于我的所有 Controller ):

    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 中收到此错误:

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"] 上中断

我应该以其他方式或其他地方做这个逻辑吗?

最佳答案

技巧是你在构造函数中不一定有上下文。相反,您应该覆盖 Initialize 方法:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
//check request context for cookie and do your thang.
}

PS:为了后人,我应该注意为什么会出现错误。异常信息的关键部分是在创建 Controller 时发生了错误,在这种情况下,无参数构造函数位是一个红鲱鱼。发生的错误是对 HttpContext 的空引用异常。

关于asp.net-mvc - asp.net mvc 无法访问基本 Controller 中的 cookie 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1358085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com