ASP NET Core Web API Post method just ignores useless fields in JSON content

Viewed 35

I created a new ASP NET Core Web API and added a simple post endpoint in the WeatherForecast boilerplate Controller:

[HttpPost]
public ActionResult<IEnumerable<WeatherForecast>> Post(WeatherForecast weather)
{
    return Ok(weather);
}

The WeatherForecast expected:

public class WeatherForecast
{
    public int TemperatureC { get; set; }
}

When I call that endpoint I'm passing the WeatherForecast with an additional field:

public class WeatherForecastDto
{
    public int TemperatureC { get; set; }
    public int Id {get; set};
}
static void Main(string[] args)
{
    HttpClient client = new()
    {
        BaseAddress = new Uri("https://localhost:7100/")
    };

    var weather = new WeatherForecastDto() { Id = 1, TemperatureC = 10 };

    var jsonContent = JsonSerializer.Serialize(weather);
    var strContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    var result = client.PostAsync("WeatherForecast/Post", strContent).Result;
}

I was expected to receive an exception since I'm passing different content than the post is expecting, But when debugging the post endpoint the ID passed by the client is just ignored.

How and why is responsible to discard the ID in the request pipeline?

2 Answers

It's the responsibility of an Input Formatter, and you can provide a custom one if you want to change the validation logic. The default behavior helps with contract evolution, at the cost being unhelpful to clients who misspell inputs.

The model binding will not be able to bind the value of id as its non-existent in the receiving end and is just ignored by the controller.

Related