Asp. net Core MVC Как добавить рецепт для текущего зарегистрированного пользователя? - PullRequest
1 голос
/ 19 февраля 2020

Как мне добавить новый рецепт для текущего зарегистрированного пользователя?

Что у меня есть: User.cs и Recipe.cs

 public class Recipe
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Ingredients { get; set; }
        public int PreparationTime { get; set; }
        public string Description { get; set; }
        public DateTime DateAdded { get; set; }
        public ICollection<RecipePhoto> RecipePhotos {get; set;}
        public User User { get; set; }
        public int UserId { get; set; }

    public class User
    {
        public int Id { get; set; }
        public string Username { get; set; }
        public byte[] PasswordHash { get; set; }
        public byte[] PasswordSalt { get; set; }
        public string Gender { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string KnownAs { get; set; }
        public DateTime Created {get; set;}
        public DateTime LastActive {get; set;}
        public string Introduction { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public ICollection<UserPhoto> UserPhotos {get; set;}
        public ICollection<Recipe> Recipes {get; set;}

    }
}

У каждого пользователя есть много (ICollection) рецептов. Что я пытаюсь сделать:

Чтобы добавить новый рецепт для текущего зарегистрированного пользователя.

В моем репо

  public async Task<Recipe> AddNewRecipe(Recipe recipe)
    {   
        await _context.Recipes.AddAsync(recipe);
        await _context.SaveChangesAsync();

        return recipe;
    }

    public async Task<bool> RecipeExists(string name)
    {
        if(await _context.Recipes.AnyAsync(r => r.Name == name))
            return true;

        return false;           
    }

UsersController

 [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private readonly IRecipesRepository _repository;
        private readonly IMapper _mapper;

        public UsersController(IRecipesRepository repository, IMapper mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }

    [HttpGet("{id}", Name = "GetUser")] // Pobieranie wartości
        public async Task<IActionResult> GetUser (int id)
        {
            var user = await _repository.GetUser(id);

            var userToReturn = _mapper.Map<UserForDetailDto>(user);

            return Ok(userToReturn);
        }


        [HttpPost("{userId}/addNewRecipe")]
        public async Task<IActionResult> AddNewRecipe(int userId, [FromForm]RecipeForCreateDto recipeForCreateDto)
        {

            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
                return Unauthorized();

            var userFromRepo = await _repository.GetUser(userId);

            recipeForCreateDto.Name = recipeForCreateDto.Name.ToLower();

            if (await _repository.RecipeExists(recipeForCreateDto.Name))
                return BadRequest("Recipe with that name already exists!");

            var recipeToCreate = _mapper.Map<Recipe>(recipeForCreateDto);

            var createdRecipe = await _repository.AddNewRecipe(recipeToCreate);

             if (await _repository.SaveAll())
            {
                var recipeToReturn = _mapper.Map<RecipeForDetailDto>(createdRecipe);
                return CreatedAtRoute("GetUser", new {controller = "Users", id = createdRecipe.Id}, recipeToReturn); 
            }

            return BadRequest("Could not add the photo");

В почтальоне, когда я пытаюсь добавить новый рецепт

(я вошел и сохранил токен-носитель), затем в http://localhost: 5000 / api / users / 1 / addNewRecipe

с содержанием:

{
    "Name": "New Recipe",
    "ingredients": "Meat, Onion",
    "preparationtime": 50,
    "Description": "lorem ipsum fooo"
}

Я ответил: 400 Плохой запрос

{
"errors": {
    "Name": [
        "The Name field is required."
    ],
    "Description": [
        "The Description field is required."
    ],
    "Ingredients": [
        "The Ingredients field is required."
    ]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|60a514fe-40bfd2ff784f9b53."

}

@ EDIT

Я изменил на FromBody и я получил 500 Внутренняя ошибка сервера enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...