Skip to content

Instantly share code, notes, and snippets.

@groovyghoul
Created March 21, 2016 12:14
Show Gist options
  • Save groovyghoul/793c71e28af0b553e9be to your computer and use it in GitHub Desktop.
Save groovyghoul/793c71e28af0b553e9be to your computer and use it in GitHub Desktop.
ASP.Net MVC set/get cookie
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Ajax.Utilities;
using Newtonsoft.Json;
namespace cookies.Controllers
{
public class CookieTestController : Controller
{
private StuffRepository _stuffRepository;
public CookieTestController()
{
_stuffRepository = new StuffRepository();
}
public ActionResult Index()
{
var stuff = _stuffRepository.GetStuff();
if (stuff != null)
{
var json = JsonConvert.SerializeObject(stuff);
var stuffCookie = new HttpCookie("stuff", json);
stuffCookie.Expires.AddDays(365);
HttpContext.Response.SetCookie(stuffCookie);
}
return View();
}
public ActionResult GetCookie()
{
if (HttpContext.Request.Cookies["stuff"] != null)
{
var stuffCookie = Request.Cookies["stuff"].Value;
var stuff = JsonConvert.DeserializeObject<Stuff>(stuffCookie);
return View(stuff);
}
throw new Exception("Could not retrieve cookie");
}
}
public class StuffRepository
{
public Stuff GetStuff()
{
var stuff = new Stuff()
{
Description = "This is stuff",
Age = 666
};
return stuff;
}
}
public class Stuff
{
public string Description { get; set; }
public int Age { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment