Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

c# - How to use content object of CreatedAtRoute?

How can I use the object sending via CreatedAtRoute without recreating?

For Example:

return CreatedAtRoute(nameof(GetUserById), new { Id = userReadDto.Id }, userReadDto);

I want to use userReadDto object without recreating in:

        [HttpGet("{id}", Name = "GetUserById")]
        public ActionResult<UserReadDto> GetUserById(int id)
        {
            var user = _repository.GetUserById(id);
            if (user != null)
                return Ok(_mapper.Map<UserReadDto>(user));
            else
                return NotFound();
        }
question from:https://stackoverflow.com/questions/65869293/how-to-use-content-object-of-createdatroute

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How to use content object of CreatedAtRoute?

You could check the definition about the CreatedAtRoute method:

enter image description here

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...