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"] 变量在被清除后从未被重新分配。

我的问题是:尝试在一定时间后仅在页面上请求查询字符串(使用 Request[“species”])还是完全发生其他事情?

我可以在我的 URL 中实际看到查询字符串,但似乎我请求的值在会话超时时不再存在。

我已经计划简单地使用隐藏的输入字段来尝试实现与上述相同的目标,但是,我认为最好在将来再次使用查询字符串之前了解以这种方式使用查询字符串的性质。

感谢您的宝贵时间,以及您可能提供的任何帮助!

4

1 回答 1

2

... Session["dBreed"] 的值从未被分配,这可能意味着 Session["species"] 变量从未被重新分配...

或者Session["species"]设置为"Feline". 查看您的第二个代码块:

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

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

于 2012-12-13T16:20:48.243 回答