使用 POSTMAN 在 Web API 中进行模型绑定后对象为空

LCJ*_*LCJ 1 rest asp.net-web-api postman

我正在尝试学习 Web API 并创建了我的第一个项目,如下所示。我正在使用邮递员测试它。post 方法工作正常,我收到响应消息 - 但控制器收到的 post 操作输入为空。需要做什么才能在控制器中获取 post 值?

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);

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

邮递员请求/响应

在此处输入图片说明

邮递员请求头 在此处输入图片说明

更新

在请求正文中使用“原始”后,它工作正常。在 POSTMAN 中,当我单击“生成代码”时,它现在显示正确的标题。

在此处输入图片说明

Mic*_*ael 5

使用 Raw 作为正文类型而不是 Form-data 并输入您的 JSON。

在此处输入图片说明