对象空POST方法Web API

时间:2019-02-27 23:53:51

标签: c# asp.net-web-api

当我使用Postman测试API的POST方法并切换到调试模式时,该方法接收的对象始终为空

enter image description here

这是我的DTO的代码:

public class CharacterDTO
{
        public int Id { get; set; }
        [Required]
        public string FirstName { get; set; }
        public string LastName { get; set; }
}

最后是我要与邮递员发送的JSON:

{
    "FirstName" : "John",
    "LastName" : "Snow"
}

如果您需要它,这是邮递员的要求:

POST /api/characters HTTP/1.1
Host: localhost:49463
Content-Type: application/json
cache-control: no-cache
Postman-Token: 1e303be2-f318-4104-b189-5142fa6ddad6
{
    "FirstName" : "John",
    "LastName" : "Snow"
}
------WebKitFormBoundary7MA4YWxkTrZu0gW--

以及我的邮递员请求的完整屏幕截图:

enter image description here

这是WebApiConfig.cs文件:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

最后是控制器:

public class CharactersController : ApiController
    {
        // GET: api/characters
        public IEnumerable<CharacterDTO> GetAllCharacters()
        {
            List<CharacterDTO> list = new List<CharacterDTO>();
            ThronesTournamentManager m = new ThronesTournamentManager();

            foreach (var element in m.GetAllCharacters())
            {
                list.Add(new CharacterDTO(element));
            }
            return list;
        }
        // GET : api/characters/{id}
        public CharacterDTO GetCharacter(int id)
        {
            Character result;
            ThronesTournamentManager m  = new ThronesTournamentManager();
            List<Character> list        = m.GetAllCharacters();

            result = list.SingleOrDefault(c => c.ID == id);

            return new CharacterDTO(result);
        }


        // POST: api/characters
        public HttpResponseMessage Post([FromBody]CharacterDTO character)
        {
            if (!ModelState.IsValid)
            {
                var errors = new List<string>();
                foreach (var state in ModelState)
                {
                    foreach (var error in state.Value.Errors)
                    {
                        errors.Add(error.ErrorMessage);
                    }
                }
                return Request.CreateResponse(HttpStatusCode.Forbidden, errors);
            }


            ThronesTournamentManager m = new ThronesTournamentManager();
            m.AddCharacter(character.Transform());

            return Request.CreateResponse(HttpStatusCode.Created, character);
        }
}

0 个答案:

没有答案