Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post json data in body to web api

I get always null value from body why ? I have no problem with using fiddler but postman is fail.

I have a web api like that:

    [Route("api/account/GetToken/")]
    [System.Web.Http.HttpPost]
    public HttpResponseBody GetToken([FromBody] string value)
    {
        string result = value;
    }

My postman data: enter image description here

and header: enter image description here

like image 824
Mennan Avatar asked May 16 '16 09:05

Mennan


People also ask

How do I POST data on Web API?

The HTTP POST request is used to create a new record in the data source in the RESTful architecture. So let's create an action method in our StudentController to insert new student record in the database using Entity Framework. The action method that will handle HTTP POST request must start with a word Post.

How do I get a value from the body of a Web API POST?

If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the . NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.


2 Answers

WebAPI is working as expected because you're telling it that you're sending this json object:

{ "username":"admin", "password":"admin" }

Then you're asking it to deserialize it as a string which is impossible since it's not a valid JSON string.

Solution 1:

If you want to receive the actual JSON as in the value of value will be:

value = "{ \"username\":\"admin\", \"password\":\"admin\" }"

then the string you need to set the body of the request in postman to is:

"{ \"username\":\"admin\", \"password\":\"admin\" }"

Solution 2 (I'm assuming this is what you want):

Create a C# object that matches the JSON so that WebAPI can deserialize it properly.

First create a class that matches your JSON:

public class Credentials
{
    [JsonProperty("username")]
    public string Username { get; set; }

    [JsonProperty("password")]
    public string Password { get; set; }
}

Then in your method use this:

[Route("api/account/GetToken/")]
[System.Web.Http.HttpPost]
public HttpResponseBody GetToken([FromBody] Credentials credentials)
{
    string username = credentials.Username;
    string password = credentials.Password;
}
like image 66
Nasreddine Avatar answered Oct 11 '22 03:10

Nasreddine


You are posting an object and trying to bind it to a string. Instead, create a type to represent that data:

public class Credentials
{
    public string Username { get; set; }
    public string Password { get; set; }
}

[Route("api/account/GetToken/")]
[System.Web.Http.HttpPost]
public HttpResponseBody GetToken([FromBody] Credentials value)
{
    string result = value.Username;
}
like image 34
Bruno Garcia Avatar answered Oct 11 '22 02:10

Bruno Garcia