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

Tow*_*hid 10 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; } 
}
Run Code Online (Sandbox Code Playgroud)

这是Fiddler拦截的POST请求 在此输入图像描述

这是我的控制者.

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

我的问题是我一直都想与null用于patient[FromBody] Patient patient

编辑1:根据ingvar的评论,我已经制作了请求体的JSON,如下所示:

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

编辑2:我ConfigureServicesConfigureStartup.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();
    }
Run Code Online (Sandbox Code Playgroud)

小智 7

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

IE{ get; set; }

希望能帮助某人。


Tow*_*hid 4

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