Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving null value in POST param

I receive a null value always in web api rest post request to a controller

In my controller

[HttpPost]
public HttpResponseMessage PostCustomer([FromBody]Customer customer)
{

       System.Diagnostics.Debug.WriteLine(customer); #CustomerApp.Models.Customer
       System.Diagnostics.Debug.WriteLine(customer.FirstName); #null

}

Model

public class Customer
{
    public int Id { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
}

Request:

POST: http://localhost:21894/api/customer/postcustomer

Content-Type: application/json

body: {FirstName: "xxxx", LastName: 'yyyy'}

I tried the following solutions but nothing works out

https://myadventuresincoding.wordpress.com/2012/06/19/c-supporting-textplain-in-an-mvc-4-rc-web-api-application/

How to get POST data in WebAPI?

Can anybody guide me with help or the correct link

Answer: Made a curl request instead of dealing with postman as like this gave me the solution

$ curl -H "Content-Type: application/json" -X POST -d '{"FirstName":"Jefferson","LastName":"sampaul"}' http://localhost
:21894/api/customer/postcustomer
like image 916
Sam Avatar asked May 17 '17 13:05

Sam


People also ask

How do I pass a null parameter in Web API?

Simply add parameterName = null in your route parameter. Another option is add an overload. Have 2 function names receive different parameters.

What does Param null mean?

If you want a parameter that can filter by a certain value, but when you have no value in your parameter, SQL returns no results. When the parameter has no value, SQL interprets it as null in your code. Null means no value. You can fix this problem by adding a code to fix the null case.

Can you use null in a parameter?

Short answer is YES, you can use null as parameter of your function as it's one of JS primitive values.


2 Answers

I think you mean to have a Customer object as input like below instead of string

public HttpResponseMessage PostCustomer([FromBody]Customer customer)
 {

Well make this below change and try reposting the request. It should work

public HttpResponseMessage PostCustomer(Customer customer)
 {
   return OK(customer.FirstName);
 }

Request:

POST: http://localhost:21894/api/customer/postcustomer
Content-Type: application/json; charset=utf-8
{"Id":101,"FirstName":"xxxx","LastName":'yyyy'}
like image 127
Rahul Avatar answered Sep 20 '22 18:09

Rahul


set your entity to be a customer not a string

[HttpPost]
public Customer PostCustomer(Customer customer)
{
    System.Diagnostics.Debug.WriteLine(customer);
    return customer;
}

Make sure you have [HttpPost] attribute on your method also no need for the [FromBody]

like image 38
johnny 5 Avatar answered Sep 20 '22 18:09

johnny 5