/// constructor used to init data members public ContactRepository() { /// HTTPContext contains all the specific information on an individual HTTP request. /// .Current means the current stream var ctx = HttpContext.Current; if (ctx != null) { if (ctx.Cache[CacheKey] == null) { var contacts = new Contact[] { new Contact { Id = 1, name = "Thomas C" }, new Contact { Id = 2, name = "Patrick C" }, new Contact { Id = 2, name = "Una C" } }; ctx.Cache[CacheKey] = contacts; } } }
/// task 3 public HttpResponseMessage Post(Contact contact) { this.contactRepository.SaveContact(contact); var response = Request.CreateResponse<Contact>(System.Net.HttpStatusCode.Created, contact); return response; }
public bool SaveContact(Contact contact) { var ctx = HttpContext.Current; if (ctx != null) { try { var currentData = ((Contact[])ctx.Cache[CacheKey]).ToList(); currentData.Add(contact); ctx.Cache[CacheKey] = currentData.ToArray(); return true; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return false; } } return false; }