简体   繁体   English

来自邮递员的POST请求未能通过模型​​验证

[英]POST request from Postman fails model validation

Inside my ASP.NET WebApi program, I have an Author model: 在我的ASP.NET WebApi程序中,我有一个Author模型:

public class Author
{
    public int Id { get; set; }
    [Required] public string Name { get; set; }
}

I also have an AuthorsController , with a PostAuthor(Author author) method: 我还有一个AuthorsController ,具有PostAuthor(Author author)方法:

// POST: api/Authors
[ResponseType(typeof(Author))]
public async Task<IHttpActionResult> PostAuthor(Author author)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    // etc.
}

When I send a POST request programmatically inside my unit tests, HTTP Status Code 201 Created is returned: 当我在单元测试中以编程方式发送POST请求时,返回HTTP Status Code 201 Created

在此处输入图片说明

However, when I send a POST request using Postman , I receive HTTP Status Code 400 Bad Request instead: 但是,当我使用Postman发送POST请求时,我收到的是HTTP Status Code 400 Bad Request

在此处输入图片说明

As you can see, when I send a POST request using Postman , the argument passed into the PostAuthor(Author author) method is null , and model validation fails as a result: 如您所见,当我使用Postman发送POST请求时,传递给PostAuthor(Author author)方法的参数为null ,因此模型验证失败:

在此处输入图片说明

What should I do to ensure that POST requests from Postman can be processed? 我应该怎么做才能确保可以处理来自Postman POST请求?

Couple of changes: define it as HttpPost and use FromBody like FromBody更改:将其定义为HttpPost并使用FromBody这样

// POST: api/Authors
[HttpPost]
[ResponseType(typeof(Author))]
public async Task<IHttpActionResult> PostAuthor([FromBody] Author author)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    // etc.
}

在邮递员正文中用=替换=,毕竟是JSON。

If you send in application/json and your API wait as INBOUND JSON, so try to send in JSON format, something like 如果您以application / json的形式发送并且您的API以INBOUND JSON的形式等待,那么尝试以JSON格式发送,例如

{
"Id":"6",
"Name":"P.G. Wodehouse"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM