这是我的模型。模型绑定不适用于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; }
}
拦截POST请求,这是我的控制器。
[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: 据英格瓦的评论,我喜欢做如下请求体的JSON:
{patient: {"name":"Leonardo","gender":"",....,"bloodGroup":""}}
但是这次我关闭了属性的默认值(例如name: ""
和age: 0
)
编辑2: 我ConfigureServices
和Configure
在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();
}
您可能需要派生api控制器或让json看起来像{patient:{name:“a”...}}。你试过这个吗? – ingvar
我已经完成了,请看看我的编辑部分。 – Towhid
它将与大写属性(如名称而不是名称)一起工作。此外,您是否尝试使用PatientController:ApiController代替PatientController:Controller? afaik [frombody]仅适用于apicontroller – ingvar