0

I have below API endpoint which has input member ID and member details. I am testing it from postman but despite passing wrong property name, API is working fine. I am not getting how its working fine.

public async Task<ActionResult<IEnumerable<Emp>>> GetStudentMarks(long rollNo, [FromBody] Subject subs)
{
//do stuff
}

My Subject class is

public class Subject
    {
        /// <summary>
        /// Array of subject names
        /// </summary>
        [Required]
        public string[] SubjectNames { get; set; }

        /// <summary>
        /// Include Last Semester Marks or not
        /// </summary>
        [Required]
        public bool? IncludeLastSemesterMarks { get; set; }

   }

When I am testing it locally in postman with below URL, its working fine.

https://localhost:7120/v1/API/getstudentmarks/1234

{
  "SubjectNames": ["English", "History"],
  "**LastSemesterMarks**": true
}

My property name in request is wrong and stil its working fine. Any idea please, why it is so

  • 1
    The property is different, not wrong. Since `IncludeLastSemesterMarks` isn't required, it doesn't have to appear in JSON. `"**LastSemesterMarks**"` is an extra property. The JSON string provided an extra property and didn't provide an optional one – Panagiotis Kanavos Jun 09 '23 at 15:45
  • Does this answer your question? [ASP.NET Core - System.Text.Json: how to reject unknown properties in payload?](https://stackoverflow.com/questions/74995241/asp-net-core-system-text-json-how-to-reject-unknown-properties-in-payload) – Panagiotis Kanavos Jun 09 '23 at 15:47
  • @PanagiotisKanavos now I have made the property as required and removed its default value as well still facing the same issue. – learningdotnet Jun 09 '23 at 16:01
  • The field is having default value which then will not be invalid. Make it field 'IncludeLastSemesterMarks' as nullable (bool?) so it will work. ref link : https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api – Levanan Gan Jun 10 '23 at 16:15
  • @LevananGan I changed it to nullable and still does not solved my problem – learningdotnet Jun 12 '23 at 10:11
  • Hi @learningdotnet, did you do something special? For example, ignore NullValue and so on. `[Required] public bool? IncludeLastSemesterMarks { get; set; }` should be right, it will give 400 error: `The IncludeLastSemesterMarks field is required.`. – Chen Jun 13 '23 at 09:16
  • @Chen I did exactly what you suggest. Its still working fine with incorrect value. – learningdotnet Jun 16 '23 at 08:31

1 Answers1

0

I found the answer for this. I added following line in my program.cs file.

builder.Services.Configure<ApiBehaviorOptions>(options
        => options.SuppressModelStateInvalidFilter = false);