Home > Back-end >  ASP NET Core Web API Post method just ignores useless fields in JSON content
ASP NET Core Web API Post method just ignores useless fields in JSON content

Time:09-17

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 a 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 is responsible to discard the ID in the request pipeline?

CodePudding user response:

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.

CodePudding user response:

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