【问题标题】:SetCookie seems to not working correctlySetCookie 似乎无法正常工作
【发布时间】:2015-08-10 07:34:15
【问题描述】:

我要做的是在后端的一些Validation 之后将cookie 设置为Response

这是我的代码:

控制器

public class MyController : Controller
{
   public ActionResult Index()
   {
       var cookie = new HttpCookie("cookie-key", "true")
        {
            Expires = DateTime.Now.AddDays(30)
        };

        System.Web.HttpContext.Current.Response.SetCookie(cookie);
   }
}

但在那之后System.Web.HttpContext.Current.Request.Cookies 中没有cookiekey "cookie-key"

我已将<sessionState cookieless="UseCookies" /> 添加到我的web.config 文件中,但它没有帮助。

我怎样才能让它正常工作?我错过了什么吗?

编辑:

我已将SetCookie 更改为Cookies.Add,但没有帮助。 更新代码:

public class MyController : Controller
{
   public ActionResult Index()
   {
       var cookie = new HttpCookie("cookie-key", "true")
       {
           Expires = DateTime.Now.AddDays(30)
       };

        System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
   }
}

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 model-view-controller


    【解决方案1】:

    试试这个代码:

     HttpCookie cookie = new HttpCookie("cookie-key","true");
                    cookie.Expires = DateTime.Now.AddDays(30);
                    cookie.Path = "/";
                    Response.Cookies.Add(cookie);
                    Response.SetCookie(cookie);
    

    1) 可能你需要写 location(path) 2) 有时 Cookies.Add AND SetCookies

    也不错

    【讨论】:

    • 您不需要SetCookie,也不需要Path 来工作。添加它没有意义,因为它“有时可能很好”......
    • Cookies.Add 将添加重复的 cookie,而 Cookies.Set 会覆盖现有的
    【解决方案2】:

    SetCookie 用于已经存在的 Cookie。

    您需要使用Response.Cookies.Add(...)

    这就是您的代码运行所需的全部内容。

    这是我在生产中 100% 工作的一些代码:

    public ActionResult Login(string username, string password)
    {
        var userService = new UserService();
    
        var loginResult = userService.ValidatePassword(username, password);
    
        if (loginResult == null) return Redirect("/");
    
        Response.Cookies.Add(new HttpCookie("tok", Uri.EscapeDataString(userService.CreateToken(loginResult)))
        {
            Expires = DateTime.Now.AddYears(1)
        });
    
        return Redirect("/admin");
    }
    

    【讨论】:

    • Response.Cookies.Add(...) 也不起作用。我认为配置有问题。
    • 尝试完全删除您的会话配置,以验证它在没有它的情况下是否正常工作。
    • 我已删除此会话配置。它没有帮助。
    • 您还有什么其他想法会导致这种行为吗?
    • 别担心,因为我无法调试您的解决方案。
    【解决方案3】:

    试试这个。

    using System.Net;
    
    var response = System.Web.HttpContext.Current.Response;
    
    foreach( Cookie cook in response.Cookies)
    {
         // set your expiration here
         cook.Expires = DateTime.MinValue;
    }
    

    【讨论】:

      【解决方案4】:

      找到了不起作用的原因。它是errorjavascript framework reactjs。有 500 internal server error 但由于 ajax call 无法诊断。

      谢谢大家的回答:)

      【讨论】:

        猜你喜欢
        • 2017-09-04
        • 2012-05-06
        • 2013-02-17
        • 2017-10-09
        • 2017-08-03
        • 2014-05-02
        • 2011-09-11
        • 2016-02-11
        • 1970-01-01
        相关资源
        最近更新 更多