Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling POST method from API controller

Tags:

c#

post

I have an API controller named MyFIlesController.

In it, I have this method:

// POST api/myfiles
public void Post([FromBody]string value)
{
}

And here's how I call it with Fiddler:

POST
URL: `http://localhost:58075/api/myfiles`

-------------------------

Request Header:

User-Agent: Fiddler

Host: localhost:58075

Content-Type: application/json

Content-length: 18

-------------

Request body:
{"value": "asjkfsf"}

The method gets called, but value is null. What am I doing wrong?

like image 419
petko_stankoski Avatar asked Feb 14 '26 06:02

petko_stankoski


2 Answers

Create a class that corresponds to your JSON:

public class Test
{
    public string value{get; set;}
    public int ID {get; set;}
}

And then change your Api-action:

// POST api/myfiles
public void Post([FromBody]Test value)
{

}

If you don't want to do that, just change the POST-body:

"somevalue"

EDIT: Added ID to the POST-payload. Now your JSON should look like this:

{"value": "someval",
"ID": 1}
like image 193
Kenneth Avatar answered Feb 15 '26 19:02

Kenneth


According to the MVC document http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1, Which exactly shows the same case as yours

Go to the Sending Simple Types part.

When you sending simple value, you need to

  1. Use FromBody Attribute

  2. the client needs to send the value with the following format:

    =value

    Specifically, the name portion of the name/value pair must be empty for a simple type.

Anyway, for further enhancement, you'd better use a complex type (an object) to accept the parameter.

like image 39
Chris Li Avatar answered Feb 15 '26 20:02

Chris Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!