SetCookie似乎无法正常工作

时间:2015-08-10 07:34:15

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

我尝试做的是在后端cookie之后将Response设置为Validation

这是我的代码:

控制器

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之后,cookie key没有"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);
   }
}

4 个答案:

答案 0 :(得分:1)

试试这段代码:

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

1)您可能需要写位置(路径) 2)有时做得好 Cookies.Add AND SetCookies

答案 1 :(得分:0)

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");
}

答案 2 :(得分:0)

试试这个。

using System.Net;

var response = System.Web.HttpContext.Current.Response;

foreach( Cookie cook in response.Cookies)
{
     // set your expiration here
     cook.Expires = DateTime.MinValue;
}

答案 3 :(得分:0)

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

谢谢大家的回答:)

相关问题