【问题标题】:Why is my PATCH request empty in an ASP.NET Controller?为什么我的 PATCH 请求在 ASP.NET 控制器中为空?
【发布时间】:2018-10-11 21:17:03
【问题描述】:

我有以下 ASP.net 核心控制器:

[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

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

问题

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

【问题讨论】:

  • 您是否尝试将[FromBody] 添加到entityPatches 参数中?
  • @DavidG Oohh no sigh 你是对的......

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


【解决方案1】:

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

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

【讨论】:

  • 我刚刚看到我可以在 ASP.Net Core 2.1 中使用 ApiControllerAttribute 和 ControllerBase 并且不再需要放置 FromBody :)
猜你喜欢
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
  • 2014-08-06
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多