Request.Cookies是null ASP.NET MVC

时间:2016-12-29 07:38:25

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

我有一个名为 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的第一个问题)

1 个答案:

答案 0 :(得分:2)

在运行构造函数时,ControllerContext未初始化,因此无法获取Request.Cookies。相反,您可以覆盖Controller.Initialize()

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