AspNetCore.Mvc 使用CreatedAtRoute返回新创建的值
使用场景:有时我们需要在创建后返回新创建的结果值,且服务端返回201的状态值
[Microsoft.AspNetCore.Mvc.NonAction] public virtual Microsoft.AspNetCore.Mvc.CreatedAtRouteResult CreatedAtRoute (string routeName, object routeValues, object content);
参数
- routeName:String
用于生成 URL 的路由的名称
- routeValues:Object
用于生成 URL 的路由数据
- content :Object
要在实体正文中设置格式的内容值 (用于设置向客户端输出需要显示数据格式)
返回
- CreatedAtRouteResult
- 参考资料页面:https://docs.microsoft.com/zh-cn/dotnet/api/system.web.http.apicontroller.createdatroute?view=aspnetcore-2.2&viewFallbackFrom=aspnetcore-5.0
- 相关代码 :
- 创建信息
public CProType insert(CProType model) { _contextRepository.InsertNow(model); return model; }
控制器:
得到数据信息
[HttpGet("{id}", Name = "getProType")] [AllowAnonymous] public JsonResult CproTypes(int id) { if (id > 0 && _proTypeService.isExists(id)) { var model = _proTypeService.getModel(id); return new JsonResult(new {code=200,data= _mapper.Map(model),msg="success" } ) ; } return new JsonResult(new { code = 404, data =new { }, msg = "没有数据" }); }
创建数据信息
[HttpPost] [AllowAnonymous] public IActionResult CproTypes([FromBody] CProTypeForCreationDTO model) { if (model != null) { model.UserId = 104616; var cproTypeModel = _mapper.Map(model); cproTypeModel=_proTypeService.insert(cproTypeModel); return CreatedAtRoute("getProType", new { id = cproTypeModel.Id }, new { code = 200, data = _mapper.Map (cproTypeModel), msg = "sucess" }); } return new JsonResult(new { code = 201, data = new { }, msg = "创建失败" }); }
返回结果:
第一个参数:routeName生成的路径 在headers中返回