2

適合你的快速場景。爲什麼我的查詢字符串值在頁面加載一段時間後丟失?

我在我的網頁試圖將值恢復到它被清除的情況下會話變量,使用查詢字符串,像這樣:

if(Session["species"] == null || Session["species"] == "") 
{ 
    Session["species"] = Request["species"]; 
} 

再往下,我設置一個值另外兩個會話變量,以關閉此會話變量的值,像這樣的:

if((string)Session["species"]=="Canine") 
{ 
    Session["dBreed"] = Request.Form["breed"].Trim(); 
} 
else if((string)Session["species"]=="Feline") 
{ 
    Session["cBreed"] = Request.Form["breed"].Trim(); 
} 

然而,似乎一旦會話超時(20分鐘之後,我相信),我仍然得到這個錯誤:

Object reference not set to an instance of an object. 

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. 

Source Error: 


Line 134:   errorMessage = "The data received from the \"Age\" field was invalid."; 
Line 135:  } 
Line 136:  if(((string)Session["dBreed"]).Length > 50) 
Line 137:  { 
Line 138:   errorMessage = "The data received from the \"Breed\" field was invalid."; 

Source File: c:\Users\cradebaugh\Documents\My Web Sites\Vaccinations\InputEntry.cshtml  

(ERRORS ON): Line: 136 

很明顯,我明白髮生了什麼(Session [「dBreed」]的值從未被賦值,這可能意味着只有Session [「species」]變量在清除後纔會被重新分配。

我的問題是:試圖請求查詢字符串(使用請求[「物種」])只有在一定的時間後在一個頁面上或完全是其他事情發生?

我可以在物理上看到我的URL和所有的查詢字符串,但似乎我請求的值在會話超時之前不再存在。

我已經計劃簡單地使用一個隱藏的輸入字段來嘗試實現與上面相同的目標,但是,我認爲最好是以這種方式理解使用查詢字符串的本質,然後再使用它們未來。

謝謝您的時間,以及您可能提供的任何幫助!

回答

2

... the value of Session["dBreed"] was never assigned, which can mean only that Session["species"] variable never got reassigned ...

或者Session["species"]設置爲"Feline"。看你的第二個代碼塊:

else if((string)Session["species"]=="Feline") 
{ 
    Session["cBreed"] = Request.Form["breed"].Trim(); 
} 

如果物種是"Feline",分配Session["cBreed"],不Session["dBreed"]

+0

看來這是怎麼回事。我忘了,即使我只打算一直調用或使用Session變量(如果它被繪製),完全忘記將它包含在我的代碼中,這意味着它會產生所述編譯器錯誤。我對這有關嗎? – VoidKing

+0

感謝您的答案,就是這樣。老實說,我應該看到這個,但是,呃,有時候很容易錯過。我很高興知道(正如我原先所想的)查詢字符串可用於(請求)而不是在有限的時間:) – VoidKing

+1

@VoidKing:它不會產生編譯器錯誤;當你試圖訪問'null'字符串的'Length'屬性時,它只是拋出一個異常。當它執行'((string)Session [「dBreed」])。Length和'Session [「dBreed」]'返回null時,Length屬性會拋出一個'NullReferenceException'。 –

相關問題