2017-07-18 69 views
0

我遇到過這樣的問題。在ASP.NET Web Api中獲取請求的身體

我在控制器中有方法,即接收POST請求體內的數據。

這裏是方法。

// POST: api/StartWorkingDays 
    [ResponseType(typeof(StartWorkingDay))] 
    public IHttpActionResult PostStartWorkingDay(StartWorkingDay startWorkingDay) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     db.StartWorkingDays.Add(startWorkingDay); 
     db.SaveChanges(); 
     return Json(new { Result = "Success", Message = "Saved Successfully"}); 
     //return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay); 
    } 

我如何看到我收到的請求的身體?

感謝您的幫助。

+0

startWorkingDay應該是您的請求的正文,並且還請檢查Request.Content – Sujith

+0

好吧,我可以看到什麼移動應用程序發送給我'startWorkingDay'?@Sujith –

+0

是的。當您調試代碼時,您可以看到startWorkingDay中填充了您發佈的內容。如果您發佈的數據與StartWorkingDay模型不同,則startWorkingDay將爲空。在這種情況下,您可以閱讀Request.Content並查看發佈到的內容。 – Sujith

回答

1
[HttpPost] 
    public HttpResponseMessage PostStartWorkingDay([FromBody] StartWorkingDay startWorkingDay) 
    { 
     //here above startWorkingDay is body your mobile developer will send 
     //you and data can be viewed while debugging , 
     //tell mobile developer to set content-type header should be JSON. 
     return Request.CreateResponse(HttpStatusCode.Created, "Success"); 
    } 

爲什麼你的返回類型是JSON?你應該使用HttpResponse。我相信你正在使用Web API 2。使用屬性路由,如果你想發送JSON格式的響應,然後從AppAStart文件夾中的WebApiConfig.cs文件中刪除Xml格式化程序

相關問題