当前位置: 代码网 > it编程>编程语言>Asp.net > 如何在 ASP.NET Core Web API 中处理 Patch 请求

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

2024年05月18日 Asp.net 我要评论
一、概述put和patch方法用于更新现有资源。 它们之间的区别是,put 会替换整个资源,而 patch 仅指定更改。在 asp.net core web api 中,由于 c# 是一种静态语言(d

一、概述

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 请求内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

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

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com