How to use content object of CreatedAtRoute?
You could check the definition about the CreatedAtRoute method:
As we can see that, the first parameter is the route Name, instead of the action name. You could check the following code to the CreatedAtRoute method:
In the Startup.Configure method, create a single route and named "default":
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index2}/{id?}");
endpoints.MapRazorPages();
});
Then, in the controller, we could use the CreatedAtRoute method like this:
return CreatedAtRoute("default", new { Id = 101 }, result); //the first parameter is the route name.
According to your code, I assume you want navigate to the GetUserById action method and transfer the data (userReadDto) between action methods. If that is the case, you could use the RedirectToAction method, code as below:
TempData.Put("data",result); //using TempData or Session to store the data.
return RedirectToAction(nameof(GetUserById), new { Id = userReadDto.Id });
Then, in the GetUserById method
[HttpGet("{id}", Name = "GetUserById")]
public ActionResult<UserReadDto> GetUserById(int id)
{
var data = TempData.Get<List<UserReadDto>>("data");
var user = _repository.GetUserById(id);
if (user != null)
return Ok(_mapper.Map<UserReadDto>(user));
else
return NotFound();
}
[Note] The above code using TempDate to store the object data, you have to add a TempDataHelper with the following code:
//required using Microsoft.AspNetCore.Mvc.ViewFeatures;
//required using System.Text.Json;
public static class TempDataHelper
{
public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
{
tempData[key] = JsonSerializer.Serialize(value);
}
public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
{
tempData.TryGetValue(key, out object o);
return o == null ? null : JsonSerializer.Deserialize<T>((string)o);
}
public static T Peek<T>(this ITempDataDictionary tempData, string key) where T : class
{
object o = tempData.Peek(key);
return o == null ? null : JsonSerializer.Deserialize<T>((string)o);
}
}
More detail information about using TempData and Session, check Session and state management in ASP.NET Core