簡體   English   中英

生成隨機數,並使用C#將其保存在Cookie中

[英]Generate random number and keep it in a cookie using c#

我正在嘗試生成隨機數,並使用c#將其保存在cookie中,這是我的cookie,名為cart

Response.Cookies["cart"].Value = RandomNumber(10, 50);
Response.Cookies["cart"].Expires = DateTime.Now.AddHours(5);

現在我在這段代碼中有一個發電機

public int RandomNumber(int min, int max)
{
  Random random = new Random();
  return random.Next(min, max);
}

我試圖將Cookie與RandomNumber相等,但出現錯誤:無法將類型'int'隱式轉換為'string'。

有什么建議嗎?

Cookie值是字符串,因此請使用ToString()int轉換為string

Response.Cookies["cart"].Value = RandomNumber(10, 50).ToString();

您不能將RandomNumber(10,50)的返回值分配給Response.Cookies [“ cart”]。Value,因為Value期望的是字符串而不是int。 嘗試在返回值上使用toString,然后將其分配給Response.Cookies [“ cart”]。Value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM