如何将null coockie值存储到字符串变量中?
问题描述:
我想尝试在下面但是抛出错误
I am trying to like below but throwing an error "
Object reference not set to an instance of an object.
"
string roll = Request.Cookies["StudentCookies"].Value;
if (roll == null || roll == String.Empty)
{
Response.Redirect("~/LoginPage.aspx");
}
答
尝试:
Try:
string roll = Request.Cookies["StudentCookies"] == null ? "" : Request.Cookies["StudentCookies"].Value;
您正在尝试使用Request.Cookies.Value而不检查它存在cookie。
这是正确的检查:
You are trying to use Request.Cookies.Value without checking it the cookie exists.
This is the correct check:
string roll = string.Empty;
// first check that cookie exists, if it does, use the value
if (Request.Cookies["StudentCookies"] != null) {
roll = Request.Cookies["StudentCookies"].Value;
}
' if cookie wasn't present or the value is empty, redirect
if ( roll == string.empty)
Response.Redirect("~/LoginPage.aspx");
Good luck.