【问题标题】:Incoming deserialized JSON always NULL传入的反序列化 JSON 始终为 NULL
【发布时间】:2016-06-15 19:27:59
【问题描述】:

我正在制作一个 WEB API 帖子,它接受 JSON 并将其转换为模型对象,以便可以将其放入数据库中。

    [HttpPost]
    [Route]
    [SwaggerResponse(HttpStatusCode.Created, CreatedMessage)]
    [SwaggerResponse(HttpStatusCode.BadRequest, BadRequestMessage, typeof(HttpError))]
    [SwaggerResponse(HttpStatusCode.Unauthorized, UnauthorizedMessage, typeof(HttpError))]
    [SwaggerResponse(HttpStatusCode.InternalServerError, UnknownErrorMessage, typeof(HttpError))]
    public async Threading.Task<IHttpActionResult> PostDocument([FromBody] Api.Document documentModel)
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        // Put the files in a temporary location
        // so then we can ReadAsMultiPartAsync and get access to the other data submitted
        var tempPath = HttpContext.Current.Server.MapPath("~/App_Data/Temp/" + Guid.NewGuid());
        Directory.CreateDirectory(tempPath);

        var deserializer = new DataContractJsonSerializer(typeof(Api.Document));
        HttpContext.Current.Request.InputStream.Position = 0;
        Api.Document docModel = (Api.Document)deserializer.ReadObject(HttpContext.Current.Request.InputStream);

        if (docModel != null)
        {
            // We don't have the json data so delete the TempFiles and return BadRequest
            Directory.Delete(tempPath, true);
            return ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest));
        }

        return await PostOrStatusCodeAsync(docModel, RouteNames.GetById).ConfigureAwait(true);
    }

但是,docModel 会标记一个警告,即它将始终为空。为什么反序列化传入的json后会为null?

【问题讨论】:

  • 在分析 (docModel != null) if 语句后设置标志。更改为 (docModel == null)。

标签: c# .net json asp.net-web-api


【解决方案1】:

关键是这样的:

    if (docModel != null)
    {
        // We don't have the json data so delete the TempFiles and return BadRequest
        Directory.Delete(tempPath, true);
        return ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest));
    }

    return await PostOrStatusCodeAsync(docModel, RouteNames.GetById).ConfigureAwait(true);
}

如果 docModel 不为 null,则返回 BadRequest。只有当 if 测试为假时,才会到达它标记它始终为 null 的位置。我怀疑您的“if”语句中的关系运算符有误。

【讨论】:

    【解决方案2】:

    在第 197 行,它将始终为空,因为如果不是,它将进入第 190 行的 if,该 if 在第 194 行返回,因此如果它不为空,则永远不会到达第 197 行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 2011-07-23
      相关资源
      最近更新 更多