コード例 #1
0
ファイル: ArticleController.cs プロジェクト: sovspace/WikiId
        public async Task <IActionResult> Create(CreateArticleViewModel model)
        {
            if (ModelState.IsValid)
            {
                var currentUser = await _userManager.GetUserAsync(HttpContext.User);

                string path = "/img/no_image.jpg";
                if (model.TitleImage != null)
                {
                    FileSaverResult fileSaverResult = await _fileSaver.SaveArticleTitleImage(_appEnvironment.WebRootPath, model.TitleImage);

                    if (fileSaverResult.IsSuccessful)
                    {
                        path = fileSaverResult.Path;
                    }
                    else
                    {
                        ModelState.AddModelError("", "Can't save image");
                    }
                }

                var result = await Mediator.Send(new CreateArticleCommand
                {
                    CategoryId     = model.CategoryId,
                    IsPublic       = model.IsPublic,
                    Title          = model.Title,
                    TitleImagePath = path,
                    IdentityUserId = currentUser.Id
                });

                if (result.IsSuccessful)
                {
                    var editArticleRoleResult = await _roleManager.CreateAsync(new IdentityRole(result.EditArticleRoleName));

                    var viewArticleRoleResult = await _roleManager.CreateAsync(new IdentityRole(result.ViewArticleRoleName));

                    if (editArticleRoleResult.Succeeded && viewArticleRoleResult.Succeeded)
                    {
                        await _userManager.AddToRoleAsync(currentUser, result.EditArticleRoleName);

                        await _userManager.AddToRoleAsync(currentUser, result.ViewArticleRoleName);

                        return(RedirectToAction("Index", "Article"));
                    }
                    else
                    {
                        await Mediator.Send(new DeleteArticleCommand { Id = result.ArticleId, IdentityUserId = currentUser.Id });

                        ModelState.AddModelError("", "Error save");
                    }
                }
                else
                {
                    ModelState.AddModelError("", result.Message);
                }
            }
            var allCategories = await Mediator.Send(new GetAllCategoriesQuery());

            if (allCategories.Any())
            {
                model.Categories = new SelectList(allCategories.Select(c => new CategoryTitleViewModel(c, c.Title)), "Id", "Title");
                return(View(model));
            }
            else
            {
                return(RedirectToAction("ErrorMessage", "Home", new { message = "No categories found" }));
            }
        }