[英]Model binding is not working on POST request in ASP.NET Core 2 WebAPI
这是我的模型。
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; }
}
这是我的控制器。
[Produces("application/json")]
[Route("api/Patient")]
public class PatientController : Controller
{
[HttpPost]
public IActionResult Post([FromBody] Patient patient)
{
//Do something with patient
return Ok();
}
}
我的问题是我总是在[FromBody] Patient patient
为patient
为null
编辑 1 :根据 ingvar 的评论,我制作了请求正文的 JSON,如下所示:
{patient: {"name":"Leonardo","gender":"",....,"bloodGroup":""}}
但这次我选择了属性的默认值(例如name: ""
和age: 0
)
编辑 2 :Startup.cs 文件中的我的ConfigureServices
和Configure
方法
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();
}
在失去一些头发后,我找到了答案。 在请求 JSON 中,我没有发送dateOfBirth
值。 这就是模型绑定器将整个patient
对象设置为null
。 所以你需要发送每个属性的正确值。
我花了整整一个小时才发现问题是我忘记在类的属性后添加 getter 和 setter。
即{ get; set; }
{ get; set; }
希望能帮助某人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.