首页 > 解决方案 > Asp .net 不在浏览器上写入 cookie

问题描述

我正在尝试使用 HttpCookie 将 cookie 写入浏览器,以下是我的方法

        private async Task WriteCookie (string userName) {

            var user = await UserManager.FindByNameAsync(userName);
            ClaimsIdentity cookiesIdentity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, cookiesIdentity);

            TokenResult token = await AuthenticationHelper.GetBearerTokenAsync(Request, user.UserName, user.Password);
            HttpCookie cookie = new HttpCookie(".myCookie");
            cookie.Value = token.access_token;
            cookie.Domain = ".myDomain"
            cookie.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(cookie);

            RedirectToAction("Dashboard", "App");

        }

我已经阅读了很多帖子,但没有一个解决方案适合我的情况,值得一提的是我已经尝试过:

  1. 删除 cookie 的域部分。
  2. 将以下设置添加到 web.config

    <httpCookies httpOnlyCookies="true" requireSSL="false" /> 
    
  3. 通过 https 运行我的网站

编辑

我使用 fiddler 跟踪了我的应用程序请求,我注意到这个请求确实使用 set-cookie 参数设置了响应标头,但是当它重定向到仪表板时,cookie 从浏览器中消失了。

我希望你们能给我一些线索来解决这个问题。

解决了

在调试此方法时发现 token.access_token 为 null,因此 cookie 的值设置为 null,因此当浏览器重定向到仪表板时,它正在删除 cookie,因为它的值为 null,我检查了生成的过程令牌有问题,我修复了它,一切又开始工作了。谢谢

标签: c#asp.net-mvccookieshttpcookie

解决方案


推荐阅读