五维思考

学习要加,骄傲要减,机会要乘,懒惰要除。 http://www.5dthink.cn

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

一、目的

我想告诉消费者我的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请求,验证结果

posted on 2020-02-14 10:36  五维思考  阅读(1841)  评论(0编辑  收藏  举报

QQ群:1. 全栈码农【346906288】2. VBA/VSTO【2660245】