【问题标题】:ASP.NET MVC can't read cookiesASP.NET MVC 无法读取 cookie
【发布时间】:2013-04-24 08:24:55
【问题描述】:

这应该很简单,尽管我发现我只能设置 cookie 而不能读回它们,尽管我的浏览器向我显示了 cookie。

在我的HomeController 中,一旦用户输入有效字符串,我就会设置 cookie:

[HttpPost]
public ActionResult Index(string fMemberCode)
{
    try
    {
        // TODO: controller-->member table module-->member data gateway-->DB
        // Check member num against member table
        //  Return cookie if exists
        //  Return error if not
        MembersModule membersModule = new MembersModule();
        int memberId = membersModule.AuthMember(fMemberCode);
        if (memberId > 0)
        {
            HttpCookie mCookie = new HttpCookie("MMedia");
            mCookie.Value = memberId.ToString();
            Response.Cookies.Add(mCookie);
        }
        else { }
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

稍后,在不同的上下文中,LibraryController 需要检查 cookie 是否存在:

public LibraryController()
{
    // TODO
    // Check member cookie present
    int id = int.Parse(Request.Cookies["Media"].Value);
    if (id > 0)
        this.module = new LibraryModule(id);
    else throw new Exception("Invalid cookie");
}

但是,当LibraryController中的执行行到达时,在VS2012中单步执行代码时:

int id = int.Parse(Request.Cookies["Media"].Value);

抛出异常:Object reference not set to an instance of an object

【问题讨论】:

  • MMedia 是您创建时的拼写错误吗? (与Media 相比)
  • 我把名字改了更合适。但问题仍然存在。
  • 您已确认 cookie 已返回给用户,并且用户在将来的请求中发回 cookie? (您说浏览器正在向您显示 cookie,但不知道 pathdomain 是否在起作用。)
  • 是的,cookie 似乎创建得很好。我通过将所有 cookie 返回到 HttpCookieCollection 进行了进一步测试,并引发了相同的异常。就好像没有 cookie 对象一样。

标签: asp.net-mvc cookies


【解决方案1】:

您无法在控制器的构造函数中访问 Request 属性。它在控制器生命周期的那个时刻不存在。

也许动作或控制器过滤器可能会对您有所帮助。

【讨论】:

  • 触摸。可能它没有注意到它在 ctor 中被引用。
  • 出色的观察力。我忘记了我在构造函数中工作!我把它放在 LibraryController Index 操作中。
猜你喜欢
  • 2018-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多