The POST method of my C# ASP.NET web api is not working

  Kiến thức lập trình

this is my post method for my api. I am creating a pokemon api tutorial following a youtube video but instead of getting succesfully created when I run it using swagger i get a 500 error

[HttpPost]
[ProducesResponseType(201, Type = typeof(OwnerDto))]
[ProducesResponseType(400)]
[ProducesResponseType(422)]
[ProducesResponseType(500)]
public IActionResult CreateOwner([FromQuery] int countryId, [FromBody] OwnerDto createOwner) {
    if(createOwner == null)
        return BadRequest(ModelState);

    var owner = _ownerRepository.GetOwners().Where(o => o.LastName.Trim().ToUpper() == createOwner.LastName.Trim().ToUpper() && o.FirstName.Trim().ToUpper() == createOwner.FirstName.Trim().ToUpper()).FirstOrDefault();

    if (owner != null)
    {
        ModelState.AddModelError("", "Owner already exists");
        return StatusCode(422, ModelState);
    }

    var ownerMap = _mapper.Map<Owner>(owner);
    ownerMap.Country = _countryRepository.GetCountry(countryId);

    if (!_ownerRepository.CreateOwner(ownerMap))
    {
        ModelState.AddModelError("", "An internal error occured");
        return StatusCode(500, ModelState);
    }

    return Ok("succesfully created");
}

this is my method to add it to my database

public bool CreateOwner(Owner owner)
{
    _context.Add(owner);
    var saved = _context.SaveChanges();
    return saved > 0 ? true : false;
}

this is the error I get refering to the ‘ownerMap.Country = _countryRepository.GetCountry(countryId);’ category line

System.NullReferenceException: Object reference not set to an instance of an object.

at PokemonReviewApp.Controllers.OwnerController.CreateOwner(Int32 countryId, OwnerDto createOwner) in C:UsersIsourcereposPokemonReviewAppPokemonReviewAppControllersOwnerController.cs:line 83

2

LEAVE A COMMENT