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
Simply add parameterName = null in your route parameter. Another option is add an overload. Have 2 function names receive different parameters.
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.
Short answer is YES, you can use null as parameter of your function as it's one of JS primitive values.
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'}
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With