模型绑定不适用于ASP.NET Core 2 WebAPI中的POST请求

时间:2017-10-15 10:11:57

标签: c# asp.net-core-webapi asp.net-core-2.0

这是我的模特。

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; } 
}

这是Fiddler拦截的POST请求 enter image description here

这是我的控制者。

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

我的问题是我null

总是patient获得[FromBody] Patient patient

编辑1 : 根据ingvar的评论,我已经提出了请求体的JSON如下:

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

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

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

2 个答案:

答案 0 :(得分:1)

我花了整整一个小时才发现问题是我忘记在类的属性后添加 getter 和 setter。

{ get; set; }

希望能帮到人。

答案 1 :(得分:0)

失去一些头发之后,我找到了答案。在请求JSON中,我没有发送dateOfBirth的值。这就是模型绑定器将整个patient对象设置为null的原因。所以你需要发送每个属性的正确值。

相关问题