示例#1
0
        public async Task <IActionResult> Post([FromBody] EventModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var seekedHost = GetEventHost(model);
                if (seekedHost == null)
                {
                    _logger.LogWarning($"User which which wants to be a host is not registered in the database");
                    return(Unauthorized());
                }

                var seeked = _repo.GetEventByName(model.Name);
                if (seeked != null)
                {
                    _logger.LogWarning($"Event with name {model.Name} already exists");
                    return(BadRequest("Could not create event"));
                }

                _logger.LogInformation($"Creating new event {model.Name}");

                var ev = Mapper.Map <Event>(model);

                ev.HostFirstName = seekedHost.FirstName;
                ev.HostLastName  = seekedHost.LastName;

                _repo.Add(ev);
                if (await _repo.SaveAllAsync())
                {
                    ev.Id = _repo.GetEventByName(ev.Name).Id;
                    _repo.Update(ev);

                    if (await _repo.SaveAllAsync())
                    {
                        var newUri = Url.Link("EventGet", new { id = ev.Id });

                        EventModel mapped = Mapper.Map <EventModel>(ev);
                        mapped.Host = Mapper.Map <UserModel>(seekedHost);
                        return(Created(newUri, mapped));
                    }
                    else
                    {
                        _logger.LogWarning("Event created but could not be updated with its host");
                    }
                }
                else
                {
                    _logger.LogWarning("Could not save event to the database");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Exception thrown while saving event: {ex}");
            }

            return(BadRequest("Could not create event"));
        }