2016-07-17 2 views
1

Web APIを学習しようとしていて、私の最初のプロジェクトを以下のように作成しました。私は郵便配達員を使ってテストしています。 postメソッドは正常に動作し、応答メッセージが表示されますが、ポスト・アクションのコントローラーで受け取った入力はnullです。コントローラのポスト値を取得するには何が必要ですか?POSTMANを使用して、Web APIのモデルバインディング後にオブジェクトがnullです

using System.Collections.Generic; 
using System.Net.Http; 
using System.Web.Http; 
using WebApplication1.Models; 

namespace WebApplication1.Controllers 
{ 
    public class ValuesController : ApiController 
    { 
     List<Comment> comments; 

     // GET api/values 
     public IEnumerable<Comment> Get() 
     { 
      return comments; 
     } 

     // GET api/values/5 
     public Comment Get(int id) 
     { 
      Comment c = comments[id-1]; 

      if (string.IsNullOrEmpty(c.Description)) 
      { 
       throw new HttpResponseException(System.Net.HttpStatusCode.NotFound); 
      } 

      return c; 
     } 

     // POST api/values 
     public HttpResponseMessage Post(Comment inputComment) 
     { 
      Comment c = new Comment(); 
      if (inputComment != null) 
      { 
       c.Description = inputComment.Description; 
       c.ID = inputComment.ID; 
      } 
      //var response = new HttpResponseMessage(HttpStatusCode.Created); 
      //return response; 

      var response = Request.CreateResponse<Comment>(System.Net.HttpStatusCode.Created, c); 
      response.Headers.Location=new System.Uri(Request.RequestUri,"/api/values/"+c.ID.ToString()); 
      return response; 
     } 

     // PUT api/values/5 
     public void Put(int id, [FromBody]string value) 
     { 
     } 

     // DELETE api/values/5 
     public void Delete(int id) 
     { 
     } 

     public ValuesController() 
     { 
      comments = new List<Comment>(); 

      Comment comment1 = new Comment(); 
      comment1.ID = 1; 
      comment1.Description = "Test1"; 

      Comment comment2 = new Comment(); 
      comment2.ID = 2; 
      comment2.Description = ""; 

      comments.Add(comment1); 
      comments.Add(comment2); 

     } 
    } 
} 

POSTMAN要求/応答

enter image description here

POSTMANリクエスト・ヘッダー enter image description here

UPDATE

リクエスト本体で 'raw'を使用した後、正常に動作しました。 POSTMANでは、「Generate Code」をクリックすると、正しいヘッダーが表示されます。代わりに、フォームデータと入力しますJSONのボディタイプとして

enter image description here

+0

方法の岩下と[FromBody]属性コメントの前に[HttpPost]を追加します。 –

答えて

関連する問題