Program Club

asp.net에서 영구 쿠키를 만드는 방법은 무엇입니까?

proclub 2020. 11. 3. 19:27
반응형

asp.net에서 영구 쿠키를 만드는 방법은 무엇입니까?


다음 줄로 쿠키를 만들고 있습니다.

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);

이제 어떻게 지속적으로 만들 수 있습니까?

브라우저를 닫은 후 같은 페이지를 다시 방문하면 되돌릴 수 없기 때문입니다.


방법은 다음과 같습니다.

영구 쿠키를 작성합니다.

//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");

//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());

//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);

//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);

영구 쿠키를 읽는 중입니다.

//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
    //No cookie found or cookie expired.
    //Handle the situation here, Redirect the user or simply return;
}

//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
    string userId = myCookie.Values["userid"].ToString();
    //Yes userId is found. Mission accomplished.
}

받아 들여진 대답은 정확하지만 원래 코드가 작동하지 않는 이유는 나와 있지 않습니다.

질문의 잘못된 코드 :

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);

두 번째 줄을보세요. 만료 기준은 기본값 1/1/0001을 포함하는 Expires 속성에 있습니다. 위 코드는 1/1/0002로 평가됩니다. 또한 평가는 속성에 다시 저장되지 않습니다. 대신 Expires 속성은 현재 날짜를 기준으로 설정해야합니다.

수정 된 코드 :

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(userid);

FWIW는 암호화되지 않은 쿠키에 사용자 ID와 같은 것을 저장하는 데 매우주의해야합니다. 이렇게하면 사이트에서 사용자가 다른 사용자를 쉽게 가장 할 수있는 쿠키 중독에 취약 해집니다. 이와 같은 것을 고려하고 있다면 양식 인증 쿠키를 직접 사용하는 것이 좋습니다.

bool persist = true;

var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);

cookie.Expires = DateTime.Now.AddMonths(3);

var ticket = FormsAuthentication.Decrypt(cookie.Value);

var userData = "store any string values you want inside the ticket
                 extra than user id that will be encrypted"

var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
     ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);

cookie.Value = FormsAuthentication.Encrypt(newTicket);

Response.Cookies.Add(cookie);

그런 다음 ASP.NET 페이지에서 언제든지 다음을 수행하여 읽을 수 있습니다.

string userId = null;
if (this.Context.User.Identity.IsAuthenticated) 
{
    userId = this.Context.User.Identity.Name;
}

ASP.NET 인증을 사용하고 쿠키를 영구적으로 설정하려면 FormsAuthenticationTicket.IsPersistent = true를 설정해야합니다. 이것이 주요 아이디어입니다.

bool isPersisted = true;
var authTicket = new FormsAuthenticationTicket(
1,
user_name, 
DateTime.Now,
DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
isPersisted,//THIS IS THE MAIN FLAG
addition_data);
    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
    if (isPersisted)
        authCookie.Expires = authTicket.Expiration;

HttpContext.Current.Response.Cookies.Add(authCookie);

이것을 마지막 줄로 추가해야합니다 ...

HttpContext.Current.Response.Cookies.Add(userid);

쿠키 값을 읽어야 할 때 다음과 유사한 방법을 사용합니다.

    string cookieUserID= String.Empty;

    try
    {
        if (HttpContext.Current.Request.Cookies["userid"] != null)
        {
            cookieUserID = HttpContext.Current.Request.Cookies["userid"];
        }
    }
    catch (Exception ex)
    {
       //handle error
    }

    return cookieUserID;

// 쿠키 추가

var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2); 
Response.Cookies.Add(panelIdCookie);

// 쿠키 읽기

    var httpCookie = Request.Cookies["panelIdCookie"];
                if (httpCookie != null)
                {
                    panelId = Convert.ToInt32(httpCookie["panelId"]);
                }

참고 URL : https://stackoverflow.com/questions/3140341/how-to-create-persistent-cookies-in-asp-net

반응형