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
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();
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With