Towhid
Towhid

Reputation: 2084

Model binding is not working on POST request in ASP.NET Core 2 WebAPI

This is my model.

public class Patient
{
  public string Name { get; set; }
  public string Gender { get; set; }
  public double Age { get; set; }
  public DateTime DateOfBirth { get; set; }
  public string MobileNumber { get; set; }
  public string Address { get; set; }
  public string Occupation { get; set; }
  public string BloodGroup { get; set; } 
}

And this is the POST request intercepted by Fiddler enter image description here

And this is my controller.

[Produces("application/json")]
[Route("api/Patient")]
public class PatientController : Controller
{        
    [HttpPost]
    public IActionResult Post([FromBody] Patient patient)
    {
       //Do something with patient
        return Ok();
    }
}

My problem is I'm always getting null for patient in [FromBody] Patient patient

EDIT 1: According to ingvar's comment I've made JSON of request body like following:

{patient: {"name":"Leonardo","gender":"",....,"bloodGroup":""}} but this time I gate default value of the properties (eg. name: "" and age: 0)

EDIT 2: My ConfigureServices and Configure method in Startup.cs file

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddMvc();

        var containerBuilder = new ContainerBuilder();
        containerBuilder.RegisterType<PatientRepository>().As<IPatientRepository>();
        containerBuilder.RegisterType<UnitOfWork>()
            .As<IUnitOfWork>()
            .WithParameter("connectionString", Configuration.GetConnectionString("PostgreConnection"));                
        containerBuilder.Populate(services);
        var container = containerBuilder.Build();
        return new AutofacServiceProvider(container);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCors(corsPolicyBuilder =>
            corsPolicyBuilder.WithOrigins("http://localhost:3000")
            .AllowAnyMethod()
            .AllowAnyHeader());
        app.UseMvc();
    }

Upvotes: 15

Views: 10410

Answers (2)

Ibrahim Hasan
Ibrahim Hasan

Reputation: 119

I spent a whole hour until I found out the problem was that I forgot to add getters and setters after class's properties.

i.e. { get; set; }

Hope to help someone.

Upvotes: 8

Towhid
Towhid

Reputation: 2084

After losing some hair I've found the answer. In the request JSON I'm not sending value of dateOfBirth. And that's why model binder is setting the whole patient object to null. So you need to send proper value of every property.

Upvotes: 4

Related Questions