C# 如何在swagger中排除请求负载中的属性

C# 如何在swagger中排除请求负载中的属性,c#,asp.net-core,swagger,asp.net-core-webapi,swagger-ui,C#,Asp.net Core,Swagger,Asp.net Core Webapi,Swagger Ui,我在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(cu

我在
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);
    }
}
顾客看起来像

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中的标识属性,它抛出错误

Cannot insert value on Identity column...
这个错误很明显,可以接受

我的要求是什么?我如何让Swagger意识到CustomerId是 在POST请求中不是请求有效负载的一部分

为Get和Post创建单独的DTO似乎是一项开销


谢谢

对于此特定场景,您可以简单地将属性设置为null,然后按如下方式对其进行装饰:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore]
public int? CustomerId { get; set; }
然后,如果它有一个值,它将出现,否则它将不会是JSON对象的一部分


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

如果您可以使用
[JsonIgnore]
属性,它应该是开箱即用的,否则您可以在这个@DarjanBogdan中找到解决方案,但我需要在Get-response-payload中包含CustomerId属性通常这是分离输入/请求和输出/响应模型的原因:)