You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 7 Minimal API中PatchAsJsonAsync请求的编写与测试

.NET 7 Minimal API Patch接口测试:PatchAsJsonAsync传递匿名对象解决方案

一、已实现的核心代码回顾

1. Person类定义

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int Age { get; set; }
}

2. MapApiEndpoints处理逻辑

public static class PersonEndpoints
{
    public static void MapPersonEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/persons");
        
        group.MapPatch("/{id}", async (int id, JsonPatchDocument<Person> patchDoc, List<Person> persons) =>
        {
            var person = persons.FirstOrDefault(p => p.Id == id);
            if (person == null)
            {
                return Results.NotFound();
            }
            
            patchDoc.ApplyTo(person);
            return Results.Ok(person);
        });
    }
}

3. Program.cs端点配置

var builder = WebApplication.CreateBuilder(args);

// 注册内存集合模拟数据库
builder.Services.AddSingleton<List<Person>>(new List<Person>
{
    new Person { Id = 1, Name = "Alice", Age = 30 }
});

var app = builder.Build();

app.MapPersonEndpoints();

app.Run();

二、PatchAsJsonAsync传递匿名对象的正确方式

直接传递new { Age = 35 }这类普通匿名对象会失败,因为JsonPatchDocument需要符合RFC 6902 JSON Patch规范的操作数组。正确做法是构造包含操作类型、路径和值的匿名对象数组:

测试代码示例(xUnit + WebApplicationFactory)

public class PersonPatchTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client;

    public PersonPatchTests(WebApplicationFactory<Program> factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task PatchPersonAge_ShouldUpdateSuccessfully()
    {
        // 构造JSON Patch操作数组:替换Age字段
        var patchOperations = new[]
        {
            new { op = "replace", path = "/age", value = 35 }
        };

        // 调用PatchAsJsonAsync传入操作数组
        var response = await _client.PatchAsJsonAsync("/api/persons/1", patchOperations);
        
        response.EnsureSuccessStatusCode();
        
        var updatedPerson = await response.Content.ReadFromJsonAsync<Person>();
        Assert.Equal(35, updatedPerson?.Age);
    }
}

关键注意点

  • 必须使用JSON Patch规范的操作类型:常用的有replace(替换字段)、add(新增字段)、remove(删除字段)等
  • path字段要匹配对象属性的JSON序列化路径(默认是驼峰命名,所以用/age而非/Age)
  • 不能直接传递普通匿名对象,必须是符合规范的操作数组

内容的提问来源于stack exchange,提问作者nathano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:22:39