2016-12-29 266 views
2

我有一個名爲StoredProcedureController控制器和我有方法CheckStoredProceduresInPerPageFromCookieRequest.Cookies時是空的ASP.NET MVC

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 ISN」 t null。 對不起,如果我的格式和問題不完美(這是我的第一個問題在stackoverflow)

+0

你如何調用這些方法?你能否提供更多關於這方面的信息,也許可以將兩個HTTP請求都添加到問題中。 –

+0

CheckStoredProceduresInPerPageFromCookie方法我打算從構造函數和ListOfStoredProcedures當我要去當前URL – DVL

+0

我將編輯我的問題 – DVL

回答

2

在運行構造函數ControllerContext的時刻沒有初始化,所以你不能得到Request.Cookies。相反,你可以重寫Controller.Initialize()

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

謝謝。我可以在mvc中設置可從我的項目的任何地方獲取的cookie嗎? (像javascript中的document.cookie) – DVL

+0

@DVL你將不得不創建一個服務來做到這一點。另外,它將與HttpContext緊密結合,並且僅在請求期間可用。 – Nkosi

+0

好的,謝謝大家。我想我會從現在發佈很多Stackoverflow :)) – DVL