【问题标题】:Read cookie https读取 cookie https
【发布时间】:2016-10-07 09:04:20
【问题描述】:

我通过以下方式收集数据并使用 POST 请求在服务器上设置 cookie:

 HttpCookie cookies = new HttpCookie(name) { 
     Value = value, 
     Expires = DateTime.MaxValue, 
     Secure = true };
 HttpContext.Current.Response.Cookies.Remove(name);
 HttpContext.Current.Response.Cookies.Add(cookies);

POST 请求完成后,我使用 js 重新加载页面。 我为该页面使用了 cookie 中的一些值。

我试着让他们喜欢:

if (HttpContext.Current.Request.Cookies[NameCookieName] != null)
{
     name = HttpContext.Current.Request.Cookies[NameCookieName].Value;
}
if (HttpContext.Current.Request.Cookies[RegionCookieName] != null)
{
     region = HttpContext.Current.Request.Cookies[RegionCookieName].Value;
}

如果我使用 HTTP,它工作正常。

当我使用 HTTPS cookie 集时,但当我读取它们时,cookie 的值为 NULL。

如何使用 HTTPS 设置/获取 cookie?

【问题讨论】:

    标签: .net asp.net-mvc cookies https


    【解决方案1】:

    我认为您必须使用安全属性。 在 C# 中的 HttpCookie 类中有一个 Secure 属性,允许您通过 HTTPS/SSL 获取和设置 cookie。我相信您需要设置条件以通过这些 HTTPS 页面以及 HTTP 页面设置和获取 cookie。

    通过 HTTPS 设置的 Cookie 应该只在 HTTP 上工作,所以也许只需使用 Secure 创建一个 cookie。听起来好像因为没有设置,所以默认情况下只在 HTTP 页面上设置 cookie。

    您可以参考以下代码:

    protected void Application_EndRequest(Object sender, EventArgs e)
        {
            string authCookie = FormsAuthentication.FormsCookieName;
    
            foreach (string sCookie in Response.Cookies)
            {
                if (sCookie.Equals(authCookie))
                {
                    // Set the cookie to be secure. Browsers will send the cookie
                    // only to pages requested with https
                    var httpCookie = Response.Cookies[sCookie];
                    if (httpCookie != null) httpCookie.Secure = true;
                }
            }
        }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2011-01-10
      • 2012-01-19
      • 1970-01-01
      • 2012-11-07
      • 2015-07-13
      • 2013-03-26
      • 2012-01-15
      • 1970-01-01
      • 2011-10-31
      相关资源
      最近更新 更多