2016-06-15 4 views
0

JSONを取り込んでモデルオブジェクトにしてデータベースに入れるWEB API投稿を作成しています。JSONは常にNULLを受け取ります

[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

フラグは、(docModel!= null)if文を解析した後に設定されます。 (docModel == null)に変更します。 –

答えて

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

オンラインでは、それがない場合は、190行目で194行目に戻り、それがヌルでない場合は197行目に達しないため、常にnullになります。

関連する問題