为什么我的PATCH请求在ASP.NET控制器中为空?

时间:2018-10-11 12:06:51

标签: c# asp.net-core postman json-patch

我有以下ASP.net Core Controller:

[ApiVersion(ApiConstants.Versions.V1)]
[Route(RouteConstants.ApiControllerPrefix + "/tenants/" + RouteConstants.TenantIdRegex + "/entities")]
public class EntityController
{
    [HttpPatch]
    [SwaggerOperation(OperationId = nameof(PatchEntity))]
    [Route("{controlId:guid}", Name = nameof(PatchEntity))]
    [SwaggerResponse(StatusCodes.Status204NoContent, "Result of the patch")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [Consumes(MediaTypes.Application.JsonPatch)]
    public async Task<IActionResult> PatchEntity(string tenantId, Guid entityId, JsonPatchDocument<EntityModel> entityPatches)
    {
        //
    }
}

控制器允许我修补现有实体。这是模型:

[JsonObject(MemberSerialization.OptIn)]
public class EntityModel
{
    [JsonProperty(PropertyName = "isAuthorized")]
    public bool IsAuthorized { get; set; }
}

为了进行测试,我使用postman在实体上发送补丁。我选择了针对该URL的动词PATCH

http://localhost:5012/api/v1/tenants/tenant-id/entities/01111111-0D1C-44D6-ABC4-2C9961F94905

在标题中,我添加了Content-Type条目并将其设置为application/json-patch+json

这是请求的正文:

[
    { "op": "replace", "path": "/isAuthorized", "value": "false" }
]

我启动了应用程序,并在控制器上设置了一个断点。使用适当的租户ID和实体ID命中断点。但是,entityPatches没有任何操作:

entityPatches.Operations.Count = 0

因此,无法更新目标IsAuthorized的属性EntityModel。我本来希望Operations属性具有一个replace操作,如HTTP请求中所定义。

问题

为什么Operations类的JsonPatchDocument属性缺少HTTP请求正文中定义的修补程序操作?

1 个答案:

答案 0 :(得分:1)

您缺少entityPatches参数上的FromBody属性,例如:

public async Task<IActionResult> PatchEntity(
    string tenantId, 
    Guid entityId, 
    [FromBody] JsonPatchDocument<EntityModel> entityPatches)
  //^^^^^^^^^^ Add this
{
    //snip
}