예제 #1
0
        public async Task <ObjectResult> Create([Bind("Title,Image,TagIds,SharingDescription")] NewsItem newsItem)
        {
            if (newsItem.Image != null)
            {
                if (!new[] { ".png", ".jpg", ".jpeg" }.Contains(Path.GetExtension(newsItem.Image.FileName)))
                {
                    ModelState.AddModelError(nameof(newsItem.Image), "Invalid image type, only png and jpg images are allowed");
                }

                if (newsItem.Image?.Length < 1)
                {
                    ModelState.AddModelError(nameof(newsItem.Image), "Filesize too small");
                }
            }

            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            if (newsItem.Image != null)
            {
                newsItem.PhotoPath = await _uploadService.Upload(newsItem.Image, "/images/uploads/newsitems");
            }

            newsItem.NewsItemTags = newsItem.TagIds?.Select(tagId => new NewsItemTag {
                NewsItem = newsItem, TagId = tagId
            }).ToList();

            newsItem.Date         = DateTime.UtcNow;
            newsItem.Language     = "nl";
            newsItem.LastModified = DateTime.UtcNow;
            try
            {
                await _newsItemRepository.Create(newsItem);

                return(new ObjectResult(newsItem.Id));
            }
            catch (DbUpdateException)
            {
                return(new ObjectResult(null)
                {
                    StatusCode = StatusCodes.Status500InternalServerError,
                });
            }
        }