如何检查cookie是否为空

Sta*_*tan 10 c# asp.net asp.net-mvc asp.net-mvc-3

我需要检查cookie是否存在有价值.但是我想知道是否有一些快速而好的方法这样做,因为如果我需要检查3个cookie,那么检查if或者看起来很糟糕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
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我有这个巨大的块来获取cookie.我想要的是这样的:

// 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);
Run Code Online (Sandbox Code Playgroud)

编辑也许我可以以某种方式覆盖.Value我喜欢的方法?

mus*_*fan 13

只需检查cookie是否为null:

if(Request.Cookies["randomHash"] != null)
{
   //do something
}
Run Code Online (Sandbox Code Playgroud)

注意:"更好"的方法是编写既可读又可靠的优秀代码.它不分配空字符串,因为这不是C#的工作方式,你试图Valuenull对象(HttpCookie)上调用属性- 你不能使用null对象,因为没有什么可以使用.

转换为int仍然需要避免解析错误,但您可以使用此内置方法:

int.TryParse(cookieString, out userID);
Run Code Online (Sandbox Code Playgroud)

这带来了另一点?为什么要将userID存储在cookie中?这可以由最终用户改变 - 我不知道你打算如何使用它,但我是否正确地认为这是一个很大的安全漏洞?


或者有一点辅助功能:

public string GetCookieValueOrDefault(string cookieName)
{
   HttpCookie cookie = Request.Cookies[cookieName];
   if(cookie == null)
   {
      return "";
   }  
   return cookie.Value;
}
Run Code Online (Sandbox Code Playgroud)

然后...

string randomHash = GetCookieValueOrDefault("randomHash");
Run Code Online (Sandbox Code Playgroud)

或者使用Extension方法:

public static string GetValueOrDefault(this HttpCookie cookie)
{
   if(cookie == null)
   {
      return "";
   }  
   return cookie.Value;  
}
Run Code Online (Sandbox Code Playgroud)

然后...

string randomHash = Request.Cookies["randomHash"].GetValueOrDefault();
Run Code Online (Sandbox Code Playgroud)

  • 一个更正你的答案很好 - int.TryParse不使用try/catch.出于效率原因,它避免了try/catch.这就是为什么使用TryParse方法而不是包装在try/catch块中总是**. (3认同)