简体   繁体   中英

How To generate cookie in C# and read with JS in MVC through HTTPS

I'm generating a cookie in C#, and attempting to read it in JQuery in an ascx on page load. The site is a mad mixture of MVC and ANgularJS, but in this instance I'm purely looking in the ascx. The site runs in https.

C# cookie generation:

    private void UpdateSessionTimerCookie(bool? loggedIn = true)
    {
        #region Not Logged in? Return nothing
        var isLoggedIn = loggedIn ?? false;
        if (!isLoggedIn) { return; }
        #endregion

        const string cookieName      = "sRoller";

        #region Delete the cookie if it already exists
        if (Request.Cookies.Exists(cookieName) && Request.Cookies[cookieName] != null)
        {
            Response.Cookies.Remove(cookieName);
            Request.Cookies.Remove(cookieName);
        }
        #endregion

        #region Build the new cookie (reset of timer)
        var cookie = new HttpCookie(cookieName)
        {
            HttpOnly  = false,
            SameSite  = SameSiteMode.Lax,
            Expires   = DateTime.Now.AddMinutes(HttpContext.Session.Timeout),
            Value     = DateTime.Now.ToString(),
            Path      = "/",
            Secure    = true,
            Shareable = false
        };

        Response.Cookies.Add(cookie);
        Response.SetCookie(cookie);
        #endregion
    }

Attempted cookie read in ascx:

<script type="text/javascript">
    $(document).ready(function() {
        function getCookie(cname) {
            var name = cname + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) === ' ') c = c.substring(1);
                if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
            }

            return "";
        }

        var myCookie = getCookie("sRoller");
        //first alert
        alert(myCookie);
    });

    function ShowCookie() {
        var MyCookie = getCookieValue("sRoller");
        //second alert
        alert(MyCookie);
    }

    function getCookieValue(name) {
        var cookieList = document.cookie.split('; ');
        var cookies = {};

        for (var i = cookieList.length - 1; i >= 0; i--) {
            var cookie = cookieList[i].split('=');
            cookies[cookie[0]] = cookie[1];
        }

        return cookies[name];
    }

    ShowCookie();
</script>

In the first alert, I get "undefined". In the second alert, I get nothing.

I've checked dev tools, and the cookie is there.

Try this:

function getCookieValue(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}

This solution is better, because you do not have to iterate over all cookies. I tested this in a private window in my browser.

More ways of getting cookies by value:

Get cookie by name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM