Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
like image 607
Towhid Avatar asked Oct 15 '17 10:10

Towhid


People also ask

How do I use FromUri in Web API?

Using [FromUri] To force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. The following example defines a GeoPoint type, along with a controller method that gets the GeoPoint from the URI.

Which of the following are relevant to model binding in Web API?

Model Binding is the most powerful mechanism in Web API 2. It enables the response to receive data as per requester choice. i.e. it may be from the URL either form of Query String or Route data OR even from Request Body. It's just the requester has to decorate the action method with [FromUri] and [FromBody] as desired.


2 Answers

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.

like image 86
Ibrahim Hasan Avatar answered Oct 16 '22 05:10

Ibrahim Hasan


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.

like image 24
Towhid Avatar answered Oct 16 '22 07:10

Towhid