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

  • 相关阅读:
    遮罩层可滚动
    toggle函数
    48.判断文本中回车的数量
    47.输出26个字母
    46.@弹出点击次数
    44.@鼠标点击页面中的任意标签,alert该标签的名称
    43.对象深度克隆
    UIscrollView 多图滑动 frame与bounds的区别比较
    累却真心充实 杂感
    delegate
  • 原文地址:https://www.cnblogs.com/zhaoshujie/p/12306481.html
Copyright © 2020-2023  润新知