2017-10-15 131 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

相關問題