Exemple #1
0
        public JsonResult Post(int nurseryId, [FromBody] ClassViewModel vm)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var newClass = Mapper.Map <Class>(vm);

                    var matchingNurs = User.FindAll("Nursery").FirstOrDefault(claim => claim.Value == nurseryId.ToString());
                    if (User.IsInRole("Admin") || matchingNurs != null)
                    {
                        newClass.Created    = DateTime.Now;
                        newClass.CreatedBy  = User.Identity.Name;
                        newClass.Modified   = DateTime.Now;
                        newClass.ModifiedBy = User.Identity.Name;
                        newClass.NurseryId  = nurseryId;

                        _repository.AddClass(nurseryId, newClass);

                        if (_repository.SaveAll())
                        {
                            Response.StatusCode = (int)HttpStatusCode.Created;
                            return(Json(Mapper.Map <ClassViewModel>(newClass)));
                        }
                    }
                    else
                    {
                        Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        return(Json($"Unauthorized to create new class in nursery {nurseryId}"));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Failed to save new class", ex);
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json("Failed to save new class"));
            }

            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return(Json("Validation failed on new class"));
        }