【发布时间】: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