在 ASP.NET Core Web API 中处理 Patch 请求
一、概述
PUT和PATCH方法用于更新现有资源。 它们之间的区别是,PUT 会替换整个资源,而 PATCH 仅指定更改。
在 ASP.NET Core Web API 中,由于 C# 是一种静态语言(dynamic 在此不表),当我们定义了一个类型用于接收 HTTP Patch 请求参数的时候,在 Action 中无法直接从实例中得知客户端提供了哪些参数。
比如定义一个输入模型和数据库实体:
public class PersonInput
{
public string? Name { get; set; }
public int? Age { get; set; }
public string? Gender { get; set; }
}
public class PersonEntity
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
再定义一个以 FromForm 形式接收参数的 Action:
[HttpPatch]
[Route("patch")]
public ActionResult Patch([FromForm] PersonInput input)
{
// 测试代码暂时将 AutoMapper 配置放在方法内。
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<PatchInput, PersonEntity>());
});
var mapper = config.CreateMapper();
// entity 从数据库读取,这里仅演示。
var entity = new PersonEntity
{
Name = "姓名", // 可能会被改变
Age = 18, // 可能会被改变
Gender = "我可能会被改变",
};
// 如果客户端只输入 Name 字段,entity 的 Age 和 Gender 将不能被正确映射或被置为 null。
mapper.Map(input, entity);
return Ok();
}
curl --location --request PATCH 'http://localhost:5094/test/patch' \
--form 'Name="foo"'
如果客户端只提供了 Name 而没有其他参数,从 HttpContext.Request.Form.Keys 可以得知这一点。如果不使用 AutoMapper,那么接下来是丑陋的判断:
var keys = _httpContextAccessor.HttpContext.Request.Form.Keys;
if(keys.Contains("Name"))
{
// 更新 Name(这里忽略合法性判断)
entity.Name = input.Name!;
}
if (keys.Contains("Age"))
{
// 更新 Age(这里忽略合法性判断)
entity.Age = input.Age!;
}
// ...
本文提供一种方式来简化这个步骤。
二、将 Keys 保存在 Input Model 中
定义一个名为 PatchInput 的类:
public abstract class PatchInput
{
[BindNever]
public ICollection<string>? PatchKeys { get; set; }
}
PatchKeys 属性不由客户端提供,不参与绑定。
PersonInput 继承自 PatchInput:
public class PersonInput : PatchInput
{
public string? Name { get; set; }
public int? Age { get; set; }
public string? Gender { get; set; }
}
三、定义 ModelBinderFactory 和 ModelBinder
public class PatchModelBinder : IModelBinder
{
private readonly IModelBinder _internalModelBinder;
public PatchModelBinder(IModelBinder internalModelBinder)
{
_internalModelBinder = internalModelBinder;
}
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
await _internalModelBinder.BindModelAsync(bindingContext);
if (bindingContext.Model is PatchInput model)
{
// 将 Form 中的 Keys 保存在 PatchKeys 中
model.PatchKeys = bindingContext.HttpContext.Request.Form.Keys;
}
}
}
public class PatchModelBinderFactory : IModelBinderFactory
{
private ModelBinderFactory _modelBinderFactory;
public PatchModelBinderFactory(
IModelMetadataProvider metadataProvider,
IOptions<MvcOptions> options,
IServiceProvider serviceProvider)
{
_modelBinderFactory = new ModelBinderFactory(metadataProvider, options, serviceProvider);
}
public IModelBinder CreateBinder(ModelBinderFactoryContext context)
{
var modelBinder = _modelBinderFactory.CreateBinder(context);
// ComplexObjectModelBinder 是 internal 类
if (typeof(PatchInput).IsAssignableFrom(context.Metadata.ModelType)
&& modelBinder.GetType().ToString().EndsWith("ComplexObjectModelBinder"))
{
modelBinder = new PatchModelBinder(modelBinder);
}
return modelBinder;
}
}
四、在 ASP.NET Core 项目中替换 ModelBinderFactory
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddPatchMapper();
AddPatchMapper 是一个简单的扩展方法:
public static class PatchMapperExtensions
{
public static IServiceCollection AddPatchMapper(this IServiceCollection services)
{
services.Replace(ServiceDescriptor.Singleton<IModelBinderFactory, PatchModelBinderFactory>());
return services;
}
}
到目前为止,在 Action 中已经能获取到请求的 Key 了。
[HttpPatch]
[Route("patch")]
public ActionResult Patch([FromForm] PersonInput input)
{
// 不需要手工给 input.PatchKeys 赋值。
return Ok();
}
PatchKeys 的作用是利用 AutoMapper。
五、定义 AutoMapper 的 TypeConverter
public class PatchConverter<T> : ITypeConverter<PatchInput, T> where T : new()
{
private static readonly IDictionary<string, Action<T, object>> _propertySetters;
static PatchConverter()
{
_propertySetters = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(p => p.Name, CreatePropertySetter);
}
private static Action<T, object> CreatePropertySetter(PropertyInfo propertyInfo)
{
var targetType = propertyInfo.DeclaringType!;
var parameterExpression = Expression.Parameter(typeof(object), "value");
var castExpression = Expression.Convert(parameterExpression, propertyInfo.PropertyType);
var targetExpression = Expression.Parameter(targetType, "target");
var propertyExpression = Expression.Property(targetExpression, propertyInfo);
var assignExpression = Expression.Assign(propertyExpression, castExpression);
var lambdaExpression = Expression.Lambda<Action<T, object>>(assignExpression, targetExpression, parameterExpression);
return lambdaExpression.Compile();
}
/// <inheritdoc />
public T Convert(PatchInput source, T destination, ResolutionContext context)
{
if (destination == null)
{
destination = new T();
}
if (source.PatchKeys == null)
{
return destination;
}
var sourceType = source.GetType();
foreach (var key in source.PatchKeys)
{
if (_propertySetters.TryGetValue(key, out var propertySetter))
{
var sourceValue = sourceType.GetProperty(key)?.GetValue(source)!;
propertySetter(destination, sourceValue);
}
}
return destination;
}
}
六、模型映射
[HttpPatch]
[Route("patch")]
public ActionResult Patch([FromForm] PersonInput input)
{
// 1. 目前仅支持 `FromForm`,即 `x-www-form_urlencoded` 和 `form-data`;暂不支持 `FromBody` 如 `raw` 等。
// 2. 使用 ModelBinderFractory 创建 ModelBinder 而不是 ModelBinderProvider 以便于未来支持更多的输入格式。
// 3. 目前还没有支持多级结构。
// 4. 测试代码暂时将 AutoMapper 配置放在方法内。
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<PatchInput, PersonEntity>().ConvertUsing(new PatchConverter<PersonEntity>());
});
var mapper = config.CreateMapper();
// PersonEntity 有 3 属性,客户端如果提供 0 或 2 个参数,在 Map 时未提供参数的属性值不会被改变。
var entity = new PersonEntity
{
Name = "姓名",
Age = 18,
Gender = "我是不会变的哦"
};
mapper.Map(input, entity);
return Ok();
}
七、测试
curl --location --request PATCH 'http://localhost:5094/test/patch' \
--form 'Name="foo"'
或
curl --location --request PATCH 'http://localhost:5094/test/patch' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'Name=foo'
源码
- 支持
FromForm,即x-www-form_urlencoded和form-data。 - 支持
FromBody如raw等。 - 支持多级结构。
参考资料
GraphQL.NET
如何在 ASP.NET Core Web API 中处理 JSON Patch 请求
在 ASP.NET Core Web API 中处理 Patch 请求的更多相关文章
- 在ASP.NET Core Web API中为RESTful服务增加对HAL的支持
HAL(Hypertext Application Language,超文本应用语言)是一种RESTful API的数据格式风格,为RESTful API的设计提供了接口规范,同时也降低了客户端与服务 ...
- [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了
[译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 本文首发自:博客园 文章地址: https://www.cnblogs.com/yilezhu/p/ ...
- C#实现多级子目录Zip压缩解压实例 NET4.6下的UTC时间转换 [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程 asp.net core异步进行新增操作并且需要判断某些字段是否重复的三种解决方案 .NET Core开发日志
C#实现多级子目录Zip压缩解压实例 参考 https://blog.csdn.net/lki_suidongdong/article/details/20942977 重点: 实现多级子目录的压缩, ...
- ASP.NET Core Web API中使用Swagger
本节导航 Swagger介绍 在ASP.NET CORE 中的使用swagger 在软件开发中,管理和测试API是一件重要而富有挑战性的工作.在我之前的文章<研发团队,请管好你的API文档& ...
- 如何在ASP.NET Core Web API中使用Mini Profiler
原文如何在ASP.NET Core Web API中使用Mini Profiler 由Anuraj发表于2019年11月25日星期一阅读时间:1分钟 ASPNETCoreMiniProfiler 这篇 ...
- ASP.NET Core Web API中带有刷新令牌的JWT身份验证流程
ASP.NET Core Web API中带有刷新令牌的JWT身份验证流程 翻译自:地址 在今年年初,我整理了有关将JWT身份验证与ASP.NET Core Web API和Angular一起使用的详 ...
- 在 ASP.NET Core Web API中使用 Polly 构建弹性容错的微服务
在 ASP.NET Core Web API中使用 Polly 构建弹性容错的微服务 https://procodeguide.com/programming/polly-in-aspnet-core ...
- 翻译一篇英文文章,主要是给自己看的——在ASP.NET Core Web Api中如何刷新token
原文地址 :https://www.blinkingcaret.com/2018/05/30/refresh-tokens-in-asp-net-core-web-api/ 先申明,本人英语太菜,每次 ...
- ASP.NET Core Web API中实现全局异常捕获与处理
处理全局异常 HANDLING ERRORS GLOBALLY 在上面的示例中,我们的 action 内部有一个 try-catch 代码块.这一点很重要,我们需要在我们的 action 方法体中处理 ...
- ASP.NET Core Web API中Startup的使用技巧
Startup类和服务配置 STARTUP CLASS AND THE SERVICE CONFIGURATION 在 Startup 类中,有两个方法:ConfigureServices 是用于 ...
随机推荐
- nios flash programer固化后不能运行
针对我的这个工程D:\works\FROM_COMP\8050\software\FPGA\MC8050_EP4CE15,出现的问题是nios eds 运行正常,有打印输出,有LED闪烁.但是flas ...
- 7. 基础增删改 - 创建管理员用Model-Drive App管理后台信息 - 在Model-Driven App中创建视图
当我们创建完Model-Driven之后,就可以在里面创建我们所需要的视图,视图一般分为三类: 个人:根据自己的个人需求创建个人视图,只有创建者和其分享的人才能查看这些视图. 公共:可以根据团体需 ...
- OD机试题-2022.4
import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.Scanne ...
- 密码破解-john的使用
john类似于hashcat一样,也是一款密码破解方式,john跟专注于系统密码的破解,并且和hashcat一样在kali中自带 hash请见hash的简单使用 重要的参数 --wordlist=字典 ...
- GO语言学习笔记-反射篇 Study for Go ! Chapter nine - Reflect
持续更新 Go 语言学习进度中 ...... GO语言学习笔记-类型篇 Study for Go! Chapter one - Type - slowlydance2me - 博客园 (cnblogs ...
- SpringBoot笔记--自动配置(高级内容)(下集)
案例需求 实现步骤: 具体的实现 1.引入Jedis依赖 2.提供Jedis的Bean 找到SpringBoot的执行文件,按住Ctrl键,进入SpringBootApplication注解,再进入E ...
- Linux & 标准C语言学习 <DAY9_1>
2.函数传参: 1.函数中定义的变量属于该函数,出了该函数就不能再被别的函数直接使用 2.实参与形参之间是以赋值的方式进行传递数据的,并且是单项值传递 ...
- Django笔记三之使用model对数据库进行增删改查
本篇笔记目录索引如下: model 准备 增 查 删 改 1.model 准备 在上一篇笔记中,我们新建了一个 application,增加了几个model 同步到了数据库,这次我们新建一个名为 bl ...
- Windows系统下Dos命令记录
# 切换到F:\test\目录 /d 参数可以直接切换,不需要先切换盘符 cd /d F:\test\ # 创建文件夹test md tset # 删除文件夹test rd test # 创建文件te ...
- Django笔记九之model查询filter、exclude、annotate、order_by
在接下来四五篇笔记中,将介绍 model 查询方法的各个细节,为我们的查询操作提供各种便利. 本篇笔记将介绍惰性查找.filter.exclude.annotate等方法,目录如下: 惰性查找 fil ...