我需要检查 cookie 是否存在价值。但我想知道是否有一些快速而好的方法可以这样做,因为如果我需要检查 3 个 cookie,用if
or来检查似乎很糟糕try
。
如果 cookie 不存在,为什么它不会为我的变量分配空字符串?相反,它显示Object reference not set to an instance of an object.
我的代码(它有效,但对于这项任务来说似乎太大了,我认为应该有更好的方法来做到这一点)
// First I need to asign empty variables and I don't like this
string randomHash = string.Empty;
string browserHash = string.Empty;
int userID = 0;
// Second I need to add this huge block of try/catch just to get cookies
// It's fine since I need all three values in this example so if one fails all fails
try
{
randomHash = Convert.ToString(Request.Cookies["randomHash"].Value);
browserHash = Convert.ToString(Request.Cookies["browserHash"].Value);
userID = Convert.ToInt32(Request.Cookies["userID"].Value);
}
catch
{
// And of course there is nothing to catch here
}
正如你所看到的,我有这么大块只是为了得到饼干。我想要的是这样的:
// Gives value on success, null on cookie that is not found
string randomHash = Convert.ToString(Request.Cookies["randomHash"].Value);
string browserHash = Convert.ToString(Request.Cookies["browserHash"].Value);
int userID = Convert.ToInt32(Request.Cookies["userID"].Value);
编辑也许我可以以某种方式覆盖.Value
我喜欢的方法?