問題描述:
POST/PUT to ASP.Net Core with [FromBody] to a MongoDB GeoJsonObjectModel member is always null
[HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] public async Task<IActionResult> CreateOrUpdateProject([FromBody]Project project) { // project is null }
其中,Project類使用了GeoJson對象。
原因分析:
1 asp.net core根據MIME類型選擇合適的序列化和反序列化器,例如application/json默認使用Json.Net庫。
2 Project對象的GeoJson成員使用的MongoDB的GeoJson對象模型,導致asp.net core反序列化該對象時失敗。
3 返回null。
解決方案:
1 取代asp.net core的默認反序列化方法,采用MongoDB的反序列化方法,代碼如下:
//POST api/v1/[controller]/ [Route("")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] public async Task<IActionResult> CreateOrUpdateProject() { //[FromBody]MonitorProject project Project project = null; using (StreamReader reader = new StreamReader(HttpContext.Request.Body, Encoding.UTF8)) { project = BsonSerializer.Deserialize<Project>(reader.ReadToEnd()); } var result = await _projectService.AddOrUpdateProject("", project); return result ? (IActionResult)Ok() : (IActionResult)BadRequest(); }