C# 使用cookie存储和调用整数

C# 使用cookie存储和调用整数,c#,asp.net,cookies,C#,Asp.net,Cookies,我正在尝试使用cookie存储开关的整数值 private int LessonSlideNum; 我得到: FormatException输入字符串的格式不正确 在这一行: LessonSlideNum = Convert.ToInt32(testCookie.Value); 或者这个: LessonSlideNum = Int.Parse(testCookie.Value); 当我使用此代码时: protected void Page_Load(object sender, Even

我正在尝试使用cookie存储开关的整数值

private int LessonSlideNum;
我得到:

FormatException输入字符串的格式不正确

在这一行:

LessonSlideNum = Convert.ToInt32(testCookie.Value);
或者这个:

LessonSlideNum = Int.Parse(testCookie.Value);
当我使用此代码时:

 protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie testCookie = Request.Cookies["TestCookie"];
        if (testCookie == null)
        {
            testCookie = new HttpCookie("TestCookie");
            testCookie.Path = "~/App_Data/Cookies";
            Response.Cookies.Add(testCookie);
        }
        else
        {
            LessonSlideNum = Convert.ToInt32(testCookie.Value);
        }
        Response.Cookies.Add(testCookie);
    }

似乎VS希望使用DateTime格式。有人能帮帮我吗?谢谢:)

错误是我在实际的cookie中没有值。谢谢阿里·沙鲁基!不过,我觉得奇怪的是:

if(testCookie == null)

未捕获此错误…

在将Cookie转换为Int32之前,Cookie的值是多少?在异常发生之前,您是否已根据调试器在断点处检查了该值?testCookie.Value=“”。当引发异常时,其值不会更改。因此错误是正确的,因为在转换时cookie中没有整数值。在将cookie转换为整数之前,必须先确保cookie具有值。在此阶段,您仅检查空值,但当您尝试将其转换为整数时,任何其他非整数值(如“”(空字符串))也会引发错误。这样做了。谢谢@AliShahrokhi!我仍然想知道为什么“if(testCookie==null)”没有捕捉到错误……因为testCookie不是null,它的值只是空的。如果(testCookie==null | | string.IsNullOrEmpty(testCookie.Value))aaaaaaaah更有意义,那么检查应该是
。有些东西不见了。谢谢@grin0048