David Tunnell David Tunnell - 5 months ago 17
JSON Question

Incoming deserialized JSON always NULL

I am working on making a WEB API post that takes in JSON and turns it into a model object so it can be put in the database.

[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);
}


However, the docModel is flagging a warning that it will always be null. Why would it be null after deserializing incoming json?

enter image description here

Answer

The key thing is this:

    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);
}

If docModel is not null, you return with BadRequest. The place it is flagging it always being null is only reached if the if test is false. I suspect you have the wrong relational operator on your 'if' statement.