CreatedAtAction doesn't work
Michel De Graeve
1
Reputation point
I need to get a URL with CreatedAtAction but get a null.
My searches did not yield any results.
**My controller**
namespace GeoService.Controllers
{
[Route("api/continent/{continentId}/country/{countryId}/City")]
[ApiController]
public class CityController : Controller
{
private readonly ICityRepository repoCity;
CityMapper cityMapper = new CityMapper();
private readonly ILogger logger;
private readonly ILogger logger2;
public CityController(ICityRepository repoCity, ILoggerFactory loggerFactor, ILogger<CityController> logger)
{
this.repoCity = repoCity;
this.logger = logger;
logger2 = loggerFactor.AddFile("./ControllerLog/City/CityControllerLogs.txt").CreateLogger("City");
}
[HttpGet("{id}")]
public ActionResult<City> Get(int id)
{
try
{
var city = repoCity.Get(id);
var result = cityMapper.Map(city, this.Url);
return Ok(result);
}
catch (CityException ex)
{
return NotFound(ex.Message);
}
}
[HttpPost]
public IActionResult POST(int continentId, int countryId, [FromBody] City city)
{
try
{
city.CountryId = countryId;
repoCity.Add(continentId, countryId, city);
return CreatedAtAction(nameof(Get), new {continentId = continentId, countryId = countryId, Id = city.Id}, cityMapper.Map(city, this.Url));
}
catch (CityException ex)
{
return NotFound(ex.Message);
}
}
**My Map**
public class CityMapper
{
public object Map(City city, IUrlHelper urlHelper)
{
return new
{
CityId = urlHelper.ActionLink("Get", "City", new
{
id = city.Id
}),
Name = city.Name,
Population = city.Population,
Capital = city.Capital
};
}
}
**The result in Postman**
{
"cityId": null, <---- no URL
"name": "New York",
"population": 8336817,
"capital": false
}
This must be the result
{
"cityId": "http://localhost:5000/api/continent/1/country/1/City/1",,
"name": "New York",
"population": 8336817,
"capital": false
}
What do I wrong.
Sign in to answer