Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

HttpCookie for C# MVC5 student

when you Create WebApp by MVC5 you need to add HttpCookie for Session or hold data in Client for Long Time Now we will do it first Check this Link for Microsoft Docs : https://docs.microsoft.com/en-us/dotnet/api/system.web.httpcookie?view=netframework-4.7.2 and Now Lit's write some Code in Controller

[HttpPost] public ActionResult Login(LoginViewModel login) { var res = _userLoginRepository.GetuserName();//this Repository for get user account //Create HttpCookie HttpCookie usercookie = new HttpCookie("log"); //Add Data inside cookie usercookie.Values.Add("name", res.userName.ToString()); usercookie.Values.Add("IDentity", Encrypt.EncryptString(res.Id.ToString(), pkey)); //Domain for cookie usercookie.Domain = "ERP.com"; //if user check remember me if (login.rememberme) { //True usercookie.Expires = DateTime.Now.AddDays(10); HttpContext.Response.Cookies.Add(usercookie); } else { //False HttpContext.Response.Cookies.Add(usercookie); } return RedirectToAction("Index"); }

Hi Mohamed,

To better understand the code you've written, here is the same but formatted:

[HttpPost] 
public ActionResult Login(LoginViewModel login) 
{ 
      var res = _userLoginRepository.GetuserName();
      //this Repository for get user account 
      //Create HttpCookie 
      HttpCookie usercookie = new HttpCookie("log"); 
      //Add Data inside cookie 
      usercookie.Values.Add("name", res.userName.ToString()); 
      usercookie.Values.Add("IDentity", Encrypt.EncryptString(res.Id.ToString(), pkey)); 
      //Domain for cookie 
      usercookie.Domain = "ERP.com"; 
      //if user check remember me 
      if (login.rememberme) 
      { 
              usercookie.Expires = DateTime.Now.AddDays(10);
              HttpContext.Response.Cookies.Add(usercookie); 
      } 
      else { 
         HttpContext.Response.Cookies.Add(usercookie); 
      } 
      return RedirectToAction("Index"); 
}