The model binder of ASP.NET Web API can't translate a JSON to a string, you must use an object to do this think.
So you have 3 options to fix your problem
First, use query string
In your action change the attribute FromBody
to FromUri
, like that
public IEnumerable<string> Post([FromUri]string custName)
{
try
{
names.Add(custName);
return names;
}
catch (Exception ex)
{
return null;
}
}
Then change your javascript code
$.post("/Api/Test/?custName=" + customerName, function(data) {
console.log(data);
}).error(function(e) {
console.log(e);
});
Second, use route attribute
Decorate your action with Route attribute like that
[Route("api/test/{custName}")]
public IEnumerable<string> Post([FromUri]string custName)
{
try
{
names.Add(custName);
return names;
}
catch (Exception ex)
{
return null;
}
}
Then change your javascript code
$.post("/Api/Test/" + customerName, function(data) {
console.log(data);
}).error(function(e) {
console.log(e);
});
Obs.: To use the Route
attribute you must configure it in WebApiConfig, so you must have this line there:
config.MapHttpAttributeRoutes();
So your WebApiConfig should be like this
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Third, use a view model class
Create a class
public class ViewModel
{
public string custName { get; set; }
}
Receive this model in your action, using FromBody attribute
public IEnumerable<string> Post([FromBody]ViewModel viewModel)
{
try
{
names.Add(viewModel.custName);
return names;
}
catch (Exception ex)
{
return null;
}
}
Then change your javascript code
$.post("/Api/Test/", { custName: customerName }, function(data) {
console.log(data);
}).error(function(e) {
console.log(e);
});
Obs.: Your controller has a little bug
public class TestController : ApiController
{
public List<string> names = new List<string>();
public string Get()
{
return "Hello I am Service";
}
//Rest of code
}
Each controller in Web API and MVC is created everytime when a request is handled by the server, so your names field in TestController class will be a new List in every request, if you want to keep data in this list other requests, make this static
public static List<string> names = new List<string>();