Asp.net Core Post参数始终为null
我从小提琴手发送POST:
POST http://localhost:55924/api/Product HTTP/1.1 User-Agent: Fiddler Host: localhost:55924 Content-Type: application/json; charset=utf-8 Content-Length: 84 {"Ean":"1122u88991","Name":"Post test","Description":"Post test desc"}
但Post方法总是为空。
// POST api/Product [HttpPost] public IActionResult PostProduct([FromBody]Product product) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _repo.Add(product); return CreatedAtRoute("GetToode",product); }
当我使用[FormBody]时,产品始终为null,当不使用时,产品会被重视,但所有字段都为null。 产品类很简单。
public class Product { public int ProductID { get; set; } public string EAN { get; set; } public string Name { get; set; } public string Description { get; set; } public int? CategoryID { get; set; } }
我尝试将NullValueHandling添加到配置服务中,但是没有用。
services.AddMvc() .AddJsonOptions(jsonOptions => { jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; });
我只需要纠正你的POST请求中的双引号就可以了。 试试这个:
{"Ean":"1122u88991","Name":"Post test","Description":"Post test desc"}
见下面的截图。
有同样的问题。 事实certificate,我没有传入实例类的公共无参数构造函数。 在这种情况下, Product
只有受保护的构造函数,无论如何,参数始终为null。 希望它对某人有帮助。