【问题标题】:Request.Cookies is null ASP.NET MVCRequest.Cookies 为空 ASP.NET MVC
【发布时间】:2017-05-13 12:18:27
【问题描述】:

我有名为 StoredProcedureController 的控制器,并且我有方法 CheckStoredProceduresInPerPageFromCookie

public class StoredProcedureController : Controller
{
    private int StoredProceduresInPerPage = 20;

    public StoredProcedureController()
    {
        CheckStoredProceduresInPerPageFromCookie();
    }

    public void CheckStoredProceduresInPerPageFromCookie()
    {
        try
        {
            if (Request.Cookies!= null)//this throws NullReferenceException
                StoredProceduresInPerPage = int.Parse(Request.Cookies["stProcsInPerPage"].Value);
        }
        catch (NullReferenceException)
        {
            try
            {
                HttpCookie stPages = new HttpCookie("stProcsInPerPage");
                stPages.Value = StoredProceduresInPerPage.ToString();
                stPages.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(stPages);//this throws nullreference exception
            }
            catch (Exception exc)
            {
                TempData["ErrorMessage"] = exc.GetBaseException().Message;
            }
        }
    }

    [RoleAuthorization("Admin_And_User")]
    [HttpGet]
    public ActionResult ListOfStoredProcedures(int page, string SearchedStoredProcedure = "", string SearchedDB = "")
    {
        if (Request.Cookies != null) 
            //I am getting here so there cookie isn't null
        ....
    }
    .....
}

我的问题是为什么CheckStoredProceduresInPerPageFromCookie Request.Cookies 为空,而ListOfStoredProcedures 不为空。 P.S 抱歉,如果我的格式和问题不完美(这是我在 stackoverflow 上的第一个问题)

【问题讨论】:

  • 你怎么称呼这些方法?您能否提供有关此的更多信息,或者将两个 HTTP 请求添加到问题中。
  • CheckStoredProceduresInPerPageFromCookie 方法我在访问当前 URL 时从构造函数和 ListOfStoredProcedures 调用
  • 我将编辑我的问题
  • 所以从哪里调用 CheckStoredProceduresInPerPageFromCookie 方法很重要?
  • 问题是,Request 对象还没有在控制器的构造函数中初始化。你需要有一个web方法来访问Cookies的请求。

标签: c# .net asp.net-mvc model-view-controller


【解决方案1】:

在运行构造函数的那一刻,ControllerContext 没有被初始化,所以你无法获取 Request.Cookies。相反,您可以覆盖 Controller.Initialize()

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
     base.Initialize(requestContext);
     CheckStoredProceduresInPerPageFromCookie();
}

【讨论】:

  • 谢谢。我可以在 mvc 中设置可以从我的项目的任何地方获取的 cookie 吗? (如 javascript 中的 document.cookie)
  • @DVL 你必须创建一个服务来做到这一点。此外,它将与 HttpContext 紧密耦合,并且仅在请求期间可用。
  • 好的,谢谢大家。我想从现在开始我会在 Stackoverflow 上发布很多内容:))
猜你喜欢
  • 2016-06-07
  • 2012-07-28
  • 1970-01-01
  • 2012-05-24
  • 1970-01-01
  • 2017-10-29
  • 2011-07-30
  • 2018-07-02
  • 2017-01-02
相关资源
最近更新 更多