【发布时间】:2018-03-27 00:09:39
【问题描述】:
这是我的模型。
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; }
}
这是我的控制器。
[Produces("application/json")]
[Route("api/Patient")]
public class PatientController : Controller
{
[HttpPost]
public IActionResult Post([FromBody] Patient patient)
{
//Do something with patient
return Ok();
}
}
我的问题是[FromBody] Patient patient 中的patient 总是得到null
编辑 1: 根据 ingvar 的评论,我制作了如下请求正文的 JSON:
{patient: {"name":"Leonardo","gender":"",....,"bloodGroup":""}}
但这次我选择了属性的默认值(例如name: "" 和age: 0)
编辑 2:
我在 Startup.cs 文件中的 ConfigureServices 和 Configure 方法
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 看起来像 {患者:{name:"a" ... }}。你试过吗?
-
我已经完成了,请查看我的编辑部分。
-
它是否适用于大写的属性(例如名称而不是名称)。另外,您是否尝试过 PatientController : ApiController 而不是 PatientController : Controller ? afaik [frombody] 仅适用于 apicontroller
-
刚刚尝试使用大写的属性。这是行不通的。这是.NET Core 2,根据andrewlock.net/model-binding-json-posts-in-asp-net-core,您需要使用
[FromBody] -
有趣。你在 configureservices (startup.cs) 中有
services.AddMvc();吗?似乎[frombody]应该适用于像{"name":"Leonardo","gender":"",....,"bloodGroup":""}这样的数据...
标签: c# asp.net-core-webapi asp.net-core-2.0