如何在 ASP.NET Webforms 中显示 cookie 值
How to show cookie value in ASP.NET Webforms
有没有什么方法可以在 ASP.NET Webforms 中显示 cookie 值,我在 ASP.NET MVC 中尝试了类似下面的代码并且它有效,但我想知道我如何才能做到这一点网络表格。
<%if (Request.Cookies["name"] != null)
{%>
<small><strong>Hello <%Request.Cookies["name"].Value.ToString();%>, Welcome!</strong></small>
<%}
else
{ %>
以上代码无效
看来您必须在页面加载时获取 cookie,然后在页面上设置它。
This 文章可能有所帮助。
您可以使用 <%=Request.Cookies["name"].Value%>
将 Cookie 的值放在页面上(注意 %=
),但是您不能像在 MVC 中那样执行条件块。所以你必须把它放在 Panel
中并控制 "visibility" 服务器端:
<asp:Panel ID="CookiePanel" runat="server">
<small><strong>Hello <%=Request.Cookies["name"].Value.ToString()%>, Welcome!</strong></asp:Panel>
</div>
然后在您的代码隐藏中,您可能会在 Page_OnLoad
中添加如下代码:
CookiePanel.Visible = (Request.Cookies["name"] != null);
请注意,当您将服务器端组件的 Visible
属性 设置为 false
时,该组件根本不会在客户端呈现,因此您赢了当 Cookie 不存在时不会出现 NullReference 错误。
有没有什么方法可以在 ASP.NET Webforms 中显示 cookie 值,我在 ASP.NET MVC 中尝试了类似下面的代码并且它有效,但我想知道我如何才能做到这一点网络表格。
<%if (Request.Cookies["name"] != null)
{%>
<small><strong>Hello <%Request.Cookies["name"].Value.ToString();%>, Welcome!</strong></small>
<%}
else
{ %>
以上代码无效
看来您必须在页面加载时获取 cookie,然后在页面上设置它。
This 文章可能有所帮助。
您可以使用 <%=Request.Cookies["name"].Value%>
将 Cookie 的值放在页面上(注意 %=
),但是您不能像在 MVC 中那样执行条件块。所以你必须把它放在 Panel
中并控制 "visibility" 服务器端:
<asp:Panel ID="CookiePanel" runat="server">
<small><strong>Hello <%=Request.Cookies["name"].Value.ToString()%>, Welcome!</strong></asp:Panel>
</div>
然后在您的代码隐藏中,您可能会在 Page_OnLoad
中添加如下代码:
CookiePanel.Visible = (Request.Cookies["name"] != null);
请注意,当您将服务器端组件的 Visible
属性 设置为 false
时,该组件根本不会在客户端呈现,因此您赢了当 Cookie 不存在时不会出现 NullReference 错误。