ASP.NET Core WebAPI inform consumers use CreatedAtRoute

First, the purpose

I want to tell consumers about the object my api newly created position of

Second, the method explained

public virtual Microsoft.AspNetCore.Mvc.CreatedAtRouteResult CreatedAtRoute (string routeName, object routeValues, object content);

Parameters

  • routeName:The name of the route to use for generating the URL.
  • routeValues:The route data to use for generating the URL.
  • content:The content value to format in the entity body.

Third, the sample code

Here's Student and not StudentDto class shows, relatively simple

[ApiController]
[Route("api/{Controller}")]
public class HomeController : Controller
{
    [HttpGet("{id}", Name = "students")]
    public IActionResult GetStudents(Guid id)
    {
        return Ok(DbContext.Db.FirstOrDefault(x => x.Id == id));
    }

    [HttpPost("student")]
    public IActionResult AddStudent([FromForm]Student student)
    {
        var stuDto = new StudentDto()
        {
            Id = Guid.NewGuid(),
            Name = student.FirstName + student.LastName,
            Age = DateTime.Now.Year - student.Birthday.Year
        };
        DbContext.Db.Add(stuDto);
        return CreatedAtRoute("students", new { id = stuDto.Id }, stuDto);
    }
}

Fourth, the test

1. Post send request, to submit the form

submit Form

2. Review the results returned

Body Return value
Body
Return value Headers
Headers

3. Copy the value of Location, sending a Get request, the verification result

Guess you like

Origin www.cnblogs.com/zhaoshujie/p/12306481.html