Reputation: 7542
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?
Upvotes: 0
Views: 99
Reputation: 605
On line 197 it will always be null because if it's not it will enter on the if on line 190 which returns on line 194 thus never reaching line 197 if it's not null.
Upvotes: 1
Reputation: 2934
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.
Upvotes: 2