ASP.NET MVC Cookie Implementation

How to create cookies in MVC 5 with C# .net?

We are using Request.Cookies for get the values of cookies and the Respone.Cookies are use to add the cookies.

In the below example, used to Respone.Cookies for create/ add new cookies. i.e.


01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
//This method id used to Create the cookies and assign the values in cookies.
private static void SetCookies(UserSession userSession)
{
    HttpCookie cookie = HttpContext.Current.Request.Cookies["GlobalCookieName"] ??
    new HttpCookie("GlobalCookieName ");
    cookie.Values["CompanyID"] = Convert.ToString(userSession.CompanyID);
    cookie.Values["TenantId"] = userSession.CompanyName;
    cookie.Values["EmailID"] = userSession.EmailID;
    cookie.Values["UserType"] = Convert.ToString(userSession.UserType);
    cookie.Expires = DateTime.Now.AddDays(365);
    HttpContext.Current.Response.Cookies.Add(cookie);
}
//This method id used to Create the cookies and assign the values in cookies.

private static void SetCookies(UserSession userSession)
{
    HttpCookie cookie = HttpContext.Current.Request.Cookies["GlobalCookieName"] ??
    new HttpCookie("GlobalCookieName ");

    cookie.Values["CompanyID"] = Convert.ToString(userSession.CompanyID);
    cookie.Values["TenantId"] = userSession.CompanyName;
    cookie.Values["EmailID"] = userSession.EmailID;
    cookie.Values["UserType"] = Convert.ToString(userSession.UserType);

    cookie.Expires = DateTime.Now.AddDays(365);
    HttpContext.Current.Response.Cookies.Add(cookie);
}
1
2
3
4
5
6
7
8
9
//This is the property class.
public class UserSession
{
     public string EmailID { get; set; }
     public int TenantID { get; set; }
     public int CompanyID { get; set; }
     public string UserType { get; set; }
}
//This is the property class.

public class UserSession
{
     public string EmailID { get; set; }
     public int TenantID { get; set; }
     public int CompanyID { get; set; }
     public string UserType { get; set; }
}
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^