I have a C# WebAPI (I'm new to web API) which work fine as I can perform GET & POST request from Postman and from another C# program using HttpClient.
The POST method is "working" since I put a breakpoint into it to check if the code in it was triggered when I send a POST request, it is.
The "another C# program" is in charge of reading some data from a DB, serializing it (with JSON.Net) & sending it to the web API.
In the web API, I want to use the JSON serialized object (which include nested objects in it) to rebuild the same object I had before serializing and sending it. Every class used to create this object exists in the webAPI program.
I think that I just have to receive the JSON string and then deserialize it to my object, but I don't acheive to get this string, instead I get 'null' as the post parameter.
My code :
WebAPI configuration
public static class SHPC_APIConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ShPcAPI",
routeTemplate: "api/{controller}/{id}",
defaults: new {id = RouteParameter.Optional}
);
// Configure JSON formatter
var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
Controller
public class DataController : ApiController
{
public string Get()
{
return "Hello world!";
}
public HttpResponseMessage Post([FromBody] string value)
{
var data = JsonConvert.DeserializeObject<Data>(value);
Console.WriteLine(value != string.Empty ? "OK" : "KO");
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
Performing a GET request works, I get the answer that I expect. Wherever I'm requesting from Postman or from my other C# program.
However, when I try to perform a POST request, the parameter value of the request is always null, wherever I'm requesting from Postman or from my other C# program.
In your WebApiConfig file into App_Start try to put this in the Register function:
var settings =
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
This will serialize all the responses in json.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.