为什么在请求不存在的 cookie 时 .NET10=] 不为 null?

Why dont .NET return null when requesting cookies that don't exist?

如果我使用以下代码检索 cookie:

Request.Cookies.Get("LoremIpsum")

如果这个 cookie 不存在,我会得到一个空的 cookie,而不是 null。这是为什么?

当我想查看响应 cookie 集合以及请求 cookie 集合时,它导致了一些问题。如果我想要的 cookie 在响应中不存在,它会在响应 cookie 集合中添加一个空 cookie,然后 return 给我。因此请求中存在的 cookie 将在页面加载后被空的响应 cookie 替换。

真的很烦人,我猜 .NET 不只是 return null 一定是有原因的?

It caused some problems

不应该,因为它是documented:

If the named cookie does not exist, this method creates a new cookie with that name.

所以不检查就不要赋值:

var cookie = Request.Cookies.Get("LoremIpsum");
if (!string.IsNullOrEmpty(cookie.Value))
{
    Response.Cookies["LoremIpsum"] = cookie;
}

或者,不要使用 Get(),而是使用 indexer,如果给定的 cookie 不存在,它会 return null:

var cookie = Request.Cookies["LoremIpsum"];
if (cookie != null)
{
    Response.Cookies["LoremIpsum"] = cookie;
}