如何在Razor页面中仅当指定Cookie存在时才插入对应HTML代码
解决方案
场景1:ASP.NET Core 项目
ASP.NET Core 中不存在HttpContext.Current用法,你可以直接使用视图内置的Context属性访问Cookie,同时需要检查Cookie值为true而非仅判断存在:
@{ var consentCookie = Context.Request.Cookies["cookieNameHere"]; if (bool.TryParse(consentCookie, out bool isConsentGiven) && isConsentGiven) { <!-- 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> } }
注意:不要从Response.Cookies读取Cookie,Response存储的是服务端将要返回给用户的Cookie集合,用户已提交的同意Cookie存储在Request.Cookies中,原代码读取位置错误会导致永远无法拿到用户已同意的标识。
场景2:ASP.NET Framework 项目
如果是Framework项目视图中无法访问HttpContext.Current,直接使用视图内置的Request对象即可:
@{ if (Request.Cookies["cookieNameHere"] != null && bool.TryParse(Request.Cookies["cookieNameHere"].Value, out bool isConsentGiven) && isConsentGiven) { <!-- 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> } }
前端实现方案(可选)
如果不想在服务端做判断,也可以直接用原生JS实现Cookie校验和GA代码动态加载:
<script> function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); } const consentVal = getCookie('cookieNameHere'); if (consentVal === 'true') { // 动态加载GA脚本 const gtagScript = document.createElement('script'); gtagScript.src = 'https://www.googletagmanager.com/gtag/js?id=idhere'; gtagScript.async = true; document.head.appendChild(gtagScript); window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-codehere'); } </script>
内容的提问来源于stack exchange,提问作者Munchkin
相关产品推荐
相关产品推荐

