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请求,验证结果

原文地址:https://www.cnblogs.com/zhaoshujie/p/12306481.html