简体   繁体   English

ASP.NET MVC Cookie实现

[英]ASP.NET MVC Cookie Implementation

I try to implement a basic cookie helper in my application.我尝试在我的应用程序中实现一个基本的 cookie 助手。 Mainly I check in base controller everytime whether or not if cookie is set.主要是我每次检查基础 controller 是否设置了 cookie。 If cookie如果饼干

public class MyCookie
{

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


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

    public void SetCookie(User user)
    {
        HttpCookie myCookie = HttpContext.Current.Request.Cookies[CookieName] ?? new HttpCookie(CookieName);
        myCookie.Values["UserId"] = user.UserId.ToString();
        myCookie.Values["LastVisit"] = DateTime.Now.ToString();
        myCookie.Expires = DateTime.Now.AddDays(365);
        HttpContext.Current.Response.Cookies.Add(myCookie);
    }

    public HttpCookie GetCookie()
    {
        HttpCookie myCookie = HttpContext.Current.Request.Cookies[CookieName];
        if(myCookie != null)
        {
            int userId = Convert.ToInt32(myCookie.Values["UserId"]);
            User user = session.Get<User>(userId);
            return user;
        }
        return null;
    }
}

if session is null I try to get from cookie or if session initialize I set cookie but I never see my cookie in browser.如果 session 是 null 我尝试从 cookie 中获取,或者如果 session 初始化我设置了 cookie 但我从未在浏览器中看到我的 cookie。 What is wrong?怎么了?

I always start session but with userId=0 To get cookie and set session from cookie:我总是启动 session 但使用 userId=0 来获取 cookie 并从 cookie 设置 session:

if (userId == 0)
{
    MyCookie myCookie = new MyCookie(_app);
    User user = cookieHelper.GetCookie();
    if (user != null)
        SessionHelper.SetSession(user);
}

You can't set and get a cookie in the same request.您不能在同一个请求中设置和获取 cookie。 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.获取 cookie 从浏览器获取,但尚未获取 - 设置 cookie 可以在请求完成时将其作为 header 的一部分发回。

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.您需要设置 cookie 并让浏览器重定向到其他地方(例如从 /login 到 /account),然后在读取新请求时它会正确显示 cookie。

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.编辑:如果猜测是错误的,我也会质疑您实际在哪里调用.SetCookie(),因为在您提供的代码中没有任何地方是您实际上调用它来首先创建 cookie。

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:例如,在新页面的 page_load 中,我输入了这个:

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.并且 cookie 正确显示没有问题。 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)因此,知道此代码确实有效,我们可以假设错误是 function 没有被调用,或者您当前正在进行的测试/调试是尝试在同一请求中设置和读取 cookie 并且失败(如我最初所述)

Either way good luck!不管怎样,祝你好运!

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)如果会话/cookie 是 null(实际上 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM