ASP.NET Core WebAPI 使用CreatedAtRoute通知消費者


一、目的

我想告訴消費者我的api關於新創建的對象的位置

二、方法說明

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.

三、示例代碼

這里的Student和StudentDto類就不展示了,比較簡單

[ApiController]
[Route("api/{Controller}")]
public class HomeController : Controller
{
	[HttpGet("students")]
	public IActionResult GetStudents()
	{
		return Ok(DbContext.Db.ToList());
	}

	[HttpGet("students/{id}", Name = nameof(GetStudents))]
	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(nameof(GetStudents), new { id = stuDto.Id }, stuDto);
	}
}

四、測試

1. 發送Post請求,提交表單

提交表單

2. 查看返回結果

返回值Body
Body

返回值Headers
Headers

3. 復制Location值,發送Get請求,驗證結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM