Gurdeep
Gurdeep

Reputation: 25

Problem sending model to HttpPost method in a .net core 3.1 web api application

I'm trying to hit my HttpPost method in a .net core 3.1 application. When i try to hit it, the model object is created but none of the properties are set. The behaviour is same when i try to invoke using Swagger as well as postman. I tried to add a model as simple as :

public class Student{
public string Name{get; set;}
}

[HttpPost]
[Route("TestMethod")]
public void TestMethod(Student stu) {}

public void TestMethod(string name) {}

The strange behaviour is, if i pass it as query string, it works, but somehow it doesn't work with json (using postman). Also, if i create a demo app, it works perfectly fine, but not with my existing application

i used FromBody attribute as well.

Can someone help me with this?

Upvotes: 1

Views: 272

Answers (1)

Serge
Serge

Reputation: 43870

you have to use this action

[HttpPost]
[Route("TestMethod")]
public IActionResult TestMethod([FromBody]Student stu) { return Ok(stu.Name)}

For a Post acton using Postman you have to select Body, raw, JSON in Postman menus. Your json should be

{ "Name":"Doe" }

Upvotes: 1

Related Questions