Inside my ASP.NET WebApi program, I have an Author
model:
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:
// 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:
However, when I send a POST
request using Postman , I receive HTTP Status Code 400 Bad Request
instead:
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:
What should I do to ensure that POST
requests from Postman
can be processed?
Couple of changes: define it as HttpPost
and use FromBody
like
// 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
{
"Id":"6",
"Name":"P.G. Wodehouse"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.