Restful API之HttpPatch

更新资源很多时候会用HttpPost和HttpPut,HttpPut会进行全局更新,如果其他属性未提供会被置为null,那如果局部更新呢?HttpPost当然也可以,如果对带宽有要求而且遵循Restful风格的话只有HttpPatch了;

1、安装包:

   映射工具:

 

 2、添加服务依赖:

services.AddControllers().AddNewtonsoftJson(setupAction =>
            {
                setupAction.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            }).AddXmlDataContractSerializerFormatters();
 services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

3、实现过程(这里省略了映射过程):

/// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="jsonPatchDocument"></param>
        /// <param name="buildingId"></param>
        /// <returns></returns>
        [HttpPatch("{buildingId}")]
        public async Task<IActionResult> UpdatePropertyItem([FromBody] JsonPatchDocument<PropertyItemForUpdateDto> jsonPatchDocument,[FromRoute] string buildingId)
        {
            var fromRepo = await _propertyItemRepository.GetPropertyItemByIDAsync(buildingId);
            var patch = _mapper.Map<PropertyItemForUpdateDto>(fromRepo);
            jsonPatchDocument.ApplyTo(patch);
            _mapper.Map(patch, fromRepo);
            var res = await _propertyItemRepository.SaveRepositoryAsync();
            return Ok(res);
        }

4、结果:

 

posted @ 2021-12-23 17:48  点终将连成线  阅读(363)  评论(0编辑  收藏  举报