2014-10-08 242 views
3

我試圖接受我的webApi端點上的application/x-www-form-urlencoded數據。當我送與具有這種Content-Type頭明確設置郵遞員的請求,我得到一個錯誤:WebApi - 請求包含實體正文,但沒有Content-Type標頭

The request contains an entity body but no Content-Type header

我的控制器:

[HttpPost] 
    [Route("api/sms")] 
    [AllowAnonymous] 
    public HttpResponseMessage Subscribe([FromBody]string Body) { // ideally would have access to both properties, but starting with one for now 
     try { 
      var messages = _messageService.SendMessage("[email protected]", Body); 
      return Request.CreateResponse(HttpStatusCode.OK, messages); 
     } catch (Exception e) { 
      return Request.CreateResponse(HttpStatusCode.InternalServerError, e); 
     } 
    } 

郵差帽:

enter image description here

我做錯了什麼?

回答

6

如果你看看請求消息,你可以看到Content-Type頭像這樣發送。

Content-Type: application/x-www-form-urlencoded, application/x-www-form-urlencoded

所以,正在手動添加Content-Type頭和郵遞員並稱爲好,因爲你已選擇的X WWW窗體-urlencoded標籤。

如果您刪除已添加的標題,它應該可以正常工作。我的意思是你不會得到一個錯誤,但綁定將不起作用,因爲簡單的類型參數[FromBody]string Body。您需要擁有這樣的操作方法。

public HttpResponseMessage Subscribe(MyClass param) { // Access param.Body here } 
public class MyClass 
{ 
    public string Body { get; set; } 
} 

相反,如果你堅持結合string Body,不要選擇X WWW的形式,進行了urlencoded選項卡。相反,選擇原始選項卡併發送=Test的正文。當然,在這種情況下,您必須手動添加'Content-Type:application/x-www-form-urlencoded'標頭。然後,正文(Test)中的值將正確綁定到參數。

enter image description here

+0

你就像WebAPI Badri的蝙蝠俠。感謝您再次拯救我的一天。 – SB2055 2014-10-08 13:54:57

相關問題