在 ASP.NET Core Web API 中处理Patch请求的方法

今天小编给大家分享的是在 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<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请求的方法就分享到这里了,希望以上内容可以对大家有一定的参考价值,可以学以致用。如果喜欢本篇文章,不妨把它分享出去让更多的人看到。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


在PHP中进行字符串拼接时,应注意以下几点: 使用 .“运算符进行字符串拼接:在PHP中,可以使用”. 运算符来连接两个字符串。 使用双引号或单引号来包裹字符...
在Python中,全局变量可以在程序的任何地方进行定义,通常在函数外部进行定义。全局变量可以在整个程序中访问,而不仅仅是在函数内部。要定义一个全局变量,只
今天小编给大家分享一下电脑显示器上auto指的是什么意思的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考
本文小编为大家详细介绍“ai建立剪切蒙版后如何移动里面的图片”,内容详细,步骤清晰,细节处理妥当,希望这篇“ai建立剪切蒙版后如何移动里面的图片”文章能帮...
这篇文章主要讲解了“windows中格式化d盘的后果是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“wind...
这篇“otf文件有哪些特点”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章...
这篇文章主要介绍“wpsystem文件夹有什么作用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“wpsystem文件夹有什
这篇文章主要介绍了ps单位指的是什么的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇ps单位指的是什么文章都会有所收获,下面我...
这篇文章主要介绍“ipv6对网速有没有提升”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“ipv6对网速有没有提升”文...
本文小编为大家详细介绍“islide是什么及有什么作用”,内容详细,步骤清晰,细节处理妥当,希望这篇“islide是什么及有什么作用”文章能帮助大家解决疑惑,下面...
本篇内容主要讲解“UAC被禁用有哪些影响”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“UAC被禁用有哪些影响”...
今天小编给大家分享一下svchost.exe可不可以关掉的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,
这篇文章主要介绍“win10有没有32位版本”,在日常操作中,相信很多人在win10有没有32位版本问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,
这篇文章主要介绍了vlookup如何引用别的表格数据的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇vlookup如何引用别的表格数据文...
本文小编为大家详细介绍“.json文件有什么作用”,内容详细,步骤清晰,细节处理妥当,希望这篇“.json文件有什么作用”文章能帮助大家解决疑惑,下面跟着小编的...
这篇文章主要介绍了vlookup函数的参数是什么意思的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇vlookup函数的参数是什么意思文...
本篇内容介绍了“wmiprvse.exe程序有什么作用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情...
这篇“Windows wifi的ip地址指的是什么”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅...
今天小编给大家分享一下video接口指的是什么的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大...
本篇内容介绍了“路由器wps有哪些优缺点”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧...