ASP.NET MVC Cookie Implementation

只愿长相守 提交于 2019-11-28 17:56:58

You can't set and get a cookie in the same request. Getting a cookie gets it from the browser and it hasn't gotten it yet - Setting a cookie preps it to be sent back as part of the header when the request has completed.

You need to set the cookie and get the browser to perhaps redirect somewhere else (eg from /login to /account) then on the new request reading it will show the cookie correctly.

EDIT: In case that guess was wrong, i would also question where you are actually calling .SetCookie() as nowhere in the code you have provided are you actually calling it to create the cookie in the first place.

To debug these things i find it good to take bits of the code you assume should work, test them. For example in the page_load of a new page i entered this:

string CookieName = "bob";
long UserId = 4;
HttpCookie myCookie = HttpContext.Current.Request.Cookies[CookieName] ?? new HttpCookie(CookieName);
myCookie.Values["UserId"] = UserId.ToString();
myCookie.Values["LastVisit"] = DateTime.Now.ToString();
myCookie.Expires = DateTime.Now.AddDays(365);
HttpContext.Current.Response.Cookies.Add(myCookie);

And the cookie appeared correctly without a problem. So knowing this code actually does work we can assume the error is the function not being called or the testing/debugging you are currentlying doing is trying to set and read the cookie in the same request and failing (as i originally stated)

Either way good luck!

gandil

My Working Implementation (Basic Version)

public class CookieHelper
{

public static string CookieName {get;set;}
public virtual Application App { get; set; }


public MyCookie(Application app)
{
    CookieName = "MyCookie" + app;
}

public static void SetCookie(User user, Community community, int cookieExpireDate = 30)
{
    HttpCookie myCookie= new HttpCookie(CookieName);
    myCookie["UserId"] = user.UserId.ToString();
    myCookie.Expires = DateTime.Now.AddDays(cookieExpireDate);
    HttpContext.Current.Response.Cookies.Add(myCookie);
 }
 }

if session/cookie is null (actually userid=0)

if (userId == 0){
    CookieHelper myCookie = new Cookie(_app);
    if (myCookie  != null)
    {
        userId = Convert.ToInt32(System.Web.HttpContext.Current.Request.Cookies[myCookie.CookieName]["userId"]);
        if(userId>0)
        {
           SessionHelper.SetSession(userId);
        }
    }
}

Try this

HttpCookie cookie = new HttpCookie("Remember_Me");
cookie["userID"] = Userid.ToString();
cookie.Expires = DateTime.Now.AddMonths(3);
Response.Cookies.Add(cookie);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!