2017-10-15 100 views
3

这是我的模型。模型绑定不适用于ASP.NET Core 2中的POST请求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; } 
} 

这是由小提琴手 enter image description here

拦截POST请求,这是我的控制器。

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

我的问题是我一直都想与nullpatient[FromBody] Patient patient

编辑1: 据英格瓦的评论,我喜欢做如下请求体的JSON:

{patient: {"name":"Leonardo","gender":"",....,"bloodGroup":""}} 但是这次我关闭了属性的默认值(例如name: ""age: 0

编辑2: 我ConfigureServicesConfigure在Startup.cs方法文件

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(); 
    } 
+0

您可能需要派生api控制器或让json看起来像{patient:{name:“a”...}}。你试过这个吗? – ingvar

+0

我已经完成了,请看看我的编辑部分。 – Towhid

+0

它将与大写属性(如名称而不是名称)一起工作。此外,您是否尝试使用PatientController:ApiController代替PatientController:Controller? afaik [frombody]仅适用于apicontroller – ingvar

回答

0

失去一些头发,我找到了答案后。在请求JSON中,我没有发送价值dateOfBirth。这就是为什么模型绑定器将整个patient对象设置为null。所以你需要发送每个财产的适当价值。

+0

如果dateOfBirth是可选的,则应在模型上使用可为空的DateTime,然后绑定应继续工作。 – natwallbank