0

I have below Endpoint in ASP.Net Core 2.1 with 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 looks as

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

    //others
}

Now the issue is in Swagger docs, the request payload for POST includes CustomerId: 0 (however optional)

So the consumer of the API passes CustomerId = someInt in the POST request, as its an Identity property in EF Core Dal, it throws the error

Cannot insert value on Identity column...

This error is quite obvious & acceptable,

what is my requirement how do I make Swagger aware that CustomerId is not part of request payload in POST request?

Creating a separate DTO for Get & Post seems an overhead.

Thanks!!

Kgn-web
  • 7,047
  • 24
  • 95
  • 161
  • If you can use `[JsonIgnore]` attribute it should work out of the box, otherwise you can find solutions in this [thread](https://stackoverflow.com/questions/41005730/how-to-configure-swashbuckle-to-ignore-property-on-model) – Darjan Bogdan Jan 10 '19 at 12:23
  • @DarjanBogdan, But I need to include the CustomerId property in Get response payload – Kgn-web Jan 10 '19 at 12:58
  • 2
    usually that is the reason to separate input/request and output/response models :) – Darjan Bogdan Jan 10 '19 at 12:59

1 Answers1

1

For this specific scenario, you can simply make the property nullable and then decorate it as follows:

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

Then, if it has a value, it will be present, otherwise it will not be part of the JSON object.

However, if you find yourself needing to change multiple different properties or adding/removing stuff for the sake of just the request or the response more than this, then @DarjanBogdan is correct: you should just use different classes for each.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444