1
웹 API를 배우려하고 다음과 같이 첫 번째 프로젝트를 작성했습니다. 우체부를 사용하여 테스트하고 있습니다. post 메서드는 잘 작동하고 응답 메시지를받습니다. 그러나 컨트롤러에서받은 후 작업에 대한 입력은 null입니다. 컨트롤러에서 포스트 값을 얻으려면 무엇을해야합니까?POSTMAN을 사용하여 웹 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 요청/응답
UPDATE
,요청 본문에서 'raw'를 사용한 후 제대로 작동했습니다. POSTMAN에서 "Generate Code"를 클릭하면 올바른 헤더가 표시됩니다.
추가 [HttpPost 상기 ontop의 방법과 [FromBody] 속성 전에 코멘트 –