gpt4 book ai didi

c# - 如何检查cookie是否为空

转载 作者:可可西里 更新时间:2023-11-01 09:05:24 24 4
gpt4 key购买 nike

我需要检查 cookie 是否存在值。但我想知道是否有一些快速而好的方法可以这样做,因为如果我需要检查 3 个 cookie,使用 iftry 进行检查似乎很糟糕。

如果 cookie 不存在,为什么它不为我的变量分配空字符串?相反,它显示 未设置对象实例的对象引用。

我的代码(它可以工作,但对于这个任务来说似乎太大了,我认为应该有更好的方法来做到这一点)

// 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
}

如您所见,我有这么大的 block 只是为了获取 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);

编辑也许我可以根据自己的喜好以某种方式覆盖 .Value 方法?

最佳答案

只检查cookie是否为空:

if(Request.Cookies["randomHash"] != null)
{
//do something
}

注意:“更好”的做法是编写既可读又可靠的好代码。它不会分配空字符串,因为这不是 C# 的工作方式,您正在尝试调用 null 对象上的 Value 属性(HttpCookie ) - 你不能使用 null 对象,因为没有什么可以使用。

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

int.TryParse(cookieString, out userID);

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


或者使用一些辅助函数:

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

然后...

string randomHash = GetCookieValueOrDefault("randomHash");

或者使用扩展方法:

public static string GetValueOrDefault(this HttpCookie cookie)
{
if(cookie == null)
{
return "";
}
return cookie.Value;
}

然后...

string randomHash = Request.Cookies["randomHash"].GetValueOrDefault();

关于c# - 如何检查cookie是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12109809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com