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?
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.
在197行上,它始终为null,因为如果不是,它将在if行上进入190行,如果在194行上返回,则如果它不为null则永远不会到达197行。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.