How to change the route format of CreatedAtAction in ASP.NET Core 2?

Clash Royale CLAN TAG#URR8PPP
How to change the route format of CreatedAtAction in ASP.NET Core 2?
In EF Core 2, the CreatedAtAction is appending the parameter as api/sample?id=1. How do I configure it to return api/sample/1?
[ApiController]
[Authorize]
[Route("api/[controller]")]
public class MyController : ControllerBase
[HttpGet("id")]
public async Task<IActionResult> Get(int id)
var entity = await service.GetAsync(id);
if (entity == null)
return NotFound(entity);
return Ok(entity);
[HttpPut]
// Other codes are omitted for brevity
public async Task<IActionResult> Create([FromBody] Entity entity)
await service.AddAsync(entity);
await service.SaveAsync();
return CreatedAtAction(action, new id = entity.Id , entity);
1 Answer
1
That is because of the route template for the action.
Most likely because of the default convention based route.
This can be fixed by placing an attribute route on the desired action with the intended route template
[Route(api/[controller])]
public class SampleController : Controller
//GET api/sample/1
[HttpGet("id")]
public IActionResult Get(int id)
//...
//POST api/sample
[HttpPost]
public IActionResult Post(Sample model)
//...
return CreatedAtAction(nameof(Get), new id = model.Id , model);
And ensuring that the correct action name is used when creating the result. The above example uses the Get action, so its route template will be used when generating the URL for the Location in the created response.
Get
Location
My API is already using the api/sample/product/1 template and pretty much all actions defaults to that template. The only thing that is returning a different route is the CreatedAtAction.
– Jeonsoft FaceBundy
Aug 7 at 17:44
@JeonsoftFaceBundy then you need to show the code that is causing the problem so a more accurate answer can be provided. Update the original question.
– Nkosi
Aug 7 at 17:45
I updated the description above. I think it's similar to your example.
– Jeonsoft FaceBundy
Aug 7 at 17:55
Actually, I already figured out the issue. I was using the nameOf(Create) as the parameter the whole time. It should be nameOf(Get)
– Jeonsoft FaceBundy
Aug 7 at 17:58
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Actually, I already figured out the issue. I was using the nameOf(Create) as the parameter the whole time. It should be nameOf(Get). Thanks!
– Jeonsoft FaceBundy
Aug 7 at 17:59