仅当 cookie 存在时,如何在 razor 页面中添加 HTML?

How do you add HTML in a razor page only if a cookie exists?

目标

如标题中所述,我希望注入一些 HTML,它会加载 Google 分析,只有在用户接受 cookie 并且特定 cookie 已设置且为真时才会激活。 我遵循了这些答案:Check if Cookie Exists

我的尝试

 @{
       using System.Net.Http;
        if (HttpContext.Current.Response.Cookies.AllKeys.Contains("cookieNameHere"))
        {
            <!-- Global site tag (gtag.js) - Google Analytics -->
            <script async src="https://www.googletagmanager.com/gtag/js?id=idhere"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-codehere');
</script>}}

错误

它抱怨 HttpContext,说它在当前上下文中不可用,因此我尝试导入它但没有任何效果...

删除不需要的 using 并简单地使用 if (Context.Request.Cookies.ContainsKey("cookieNameHere")) :

 @{
        if (Context.Request.Cookies.ContainsKey("cookieNameHere"))
        {
            <!-- Global site tag (gtag.js) - Google Analytics -->
            <script async src="https://www.googletagmanager.com/gtag/js?id=idhere"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-codehere');
</script>}}