如何在 ASP.NET Core Web API 中处理 Patch 请求

2023-12-08 0 872
目录
  • 一、概述
  • 二、将 Keys 保存在 Input Model 中
  • 三、定义 ModelBinderFactory 和 ModelBinder
  • 四、在 ASP.NET Core 项目中替换 ModelBinderFactory
  • 五、定义 AutoMapper 的 TypeConverter
  • 六、模型映射
  • 七、测试
  • 源码
  • 参考资料

一、概述

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<PersonInput, 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()
{
/// <inheritdoc />
public T Convert(PatchInput source, T destination, ResolutionContext context)
{
destination ??= new T();
var sourceType = source.GetType();
var destinationType = typeof(T);
foreach (var key in source.PatchKeys ?? Enumerable.Empty<string>())
{
var sourcePropertyInfo = sourceType.GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (sourcePropertyInfo != null)
{
var destinationPropertyInfo = destinationType.GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (destinationPropertyInfo != null)
{
var sourceValue = sourcePropertyInfo.GetValue(source);
destinationPropertyInfo.SetValue(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<PersonInput, PersonEntity>().ConvertUsing(new PatchConverter<PersonEntity>());
});
var mapper = config.CreateMapper();
// PersonEntity 有 3 个属性,客户端如果提供的参数参数不足 3 个,在 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\’

源码

Tubumu.PatchMapper

  • 支持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 处理 Patch 请求内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!

您可能感兴趣的文章:

  • Asp.Net Core添加请求头自定义认证的示例
  • 在ASP.NET Core中用HttpClient发送POST, PUT和DELETE请求
  • ASP.NET Core MVC获取请求的参数方法示例
  • Asp.Net Core控制器如何接收原始请求正文内容详解
  • 使用NLog给Asp.Net Core做请求监控的方法
  • 如何ASP.NET Core Razor中处理Ajax请求
  • ASP.NET Core中调整HTTP请求大小的几种方法详解

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 ASP.NET 如何在 ASP.NET Core Web API 中处理 Patch 请求 https://www.u-9.cn/biancheng/aspnet/128474.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务