【问题标题】:How to exclude property in Request payload in swagger如何在招摇中排除请求有效负载中的属性
【发布时间】:2019-06-05 07:02:26
【问题描述】:

我在ASP.Net Core 2.1 和EF Core 2.1 中有以下端点

  public class CustomerController
{
    public IActionResult Post([FromBody]CustomerTO customer)
    {

    }

    public IActionResult Get(int id)
    {
        var customer = _dal.GetCustomer(id);
        return Ok(customer);
    }
}

CustomerTO 看起来像

public class CustomerTO
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }

    //others
}

现在问题出在 Swagger 文档中,POST 的请求负载包括 CustomerId: 0(但可选)

所以 API 的使用者在 POST 请求中传递 CustomerId = someInt,作为它在 EF Core Dal 中的一个 Identity 属性,它会抛出错误

Cannot insert value on Identity column...

这个错误很明显并且可以接受,

我的要求是什么我如何让 Swagger 知道 CustomerId 是 不是 POST 请求中请求负载的一部分?

为 Get & Post 创建单独的 DTO 似乎是一种开销。

谢谢!!

【问题讨论】:

  • 如果您可以使用[JsonIgnore] 属性,它应该开箱即用,否则您可以在此thread 中找到解决方案
  • @DarjanBogdan,但我需要在获取响应负载中包含 CustomerId 属性
  • 通常这就是将输入/请求和输出/响应模型分开的原因:)

标签: c# asp.net-core swagger asp.net-core-webapi swagger-ui


【解决方案1】:

对于这个特定的场景,您可以简单地使属性为空,然后按如下方式装饰它:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore]
public int? CustomerId { get; set; }

然后,如果它有一个值,它就会存在,否则它不会是 JSON 对象的一部分。

但是,如果您发现自己需要更改多个不同的属性或添加/删除内容只是为了请求或响应,那么@DarjanBogdan 是正确的:您应该为每个使用不同的类。

【讨论】:

    猜你喜欢
    • 2017-08-16
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    相关资源
    最近更新 更多