传入的反序列化JSON始终为NULL

时间:2016-06-15 19:27:59

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

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

    [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正在标记一个警告,它始终为null。为什么在反序列化传入的json后它会为null?

enter image description here

2 个答案:

答案 0 :(得分:2)

关键是:

    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测试为false时,才会标记它始终为null的标记位置。我怀疑你的'if'语句中有错误的关系运算符。

答案 1 :(得分:1)

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