zoukankan      html  css  js  c++  java
  • 问题:调用 ASP.Net Core WebAPI的HTTP POST方法时,从 [FromBody] 中读取的 MongoDB GeoJsonObjectModel成员总是null

    问题描述:

    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();
            }
  • 相关阅读:
    Mysql安装(msi版的安装)
    001 springBoot的数据库操作
    使用IDEA搭建spring
    spring简介
    rabbitMQ的安装(Windows下)
    mysql过滤数据
    mysql查询数据
    均值滤波,中值滤波,最大最小值滤波
    图像运动去模糊(Motion Deblurring)代码
    数字图像处理,图像锐化算法的C++实现
  • 原文地址:https://www.cnblogs.com/dadream/p/7867170.html
Copyright © 2011-2022 走看看