简体   繁体   中英

ASP.NET Web API receives a null as parameter in POST when called from R

I have created a Web API in ASP.NET MVC 4 using Visual Studio 2012. I am using a POST method to receive data sent by the user/calling application.

[HttpPost]
public HttpResponseMessage Post(Object model)
{
    HttpResponseMessage hrm;
    try
    {
        if (model == null)
        {
            hrm = new HttpResponseMessage(HttpStatusCode.NotFound);
            hrm.Content = new StringContent("Null request data");
            hrm.ReasonPhrase = "Incomming contract info is NULL";

            return hrm;
        }
        InputData IDat = JsonConvert.DeserializeObject<InputData>(model.ToString());
        ...

When I test the POST to the API using HttpClient.PostAsJsonAsync with the following code,

HttpClient hc = new HttpClient();
string resp = "";
if (idat.GetType().Name == "InputData")
{
    hc = new HttpClient();
    hc.BaseAddress = new Uri("http://localhost:49688/");
    hc.DefaultRequestHeaders.Accept.Clear();
    hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var response = hc.PostAsJsonAsync("API/ ComputeFR", idat).Result;
    resp = response.Content.ReadAsStringAsync().Result;
    ...

The web API receives the JSON, model above is not null, and it shows the JSON sent by the calling routine. The JSON sent looks like this:

{
  "UserId": "test",
  "pwd": "test123",
  "ContractParam": [
    {
      "ContractID": "00000",
      "Units": [
        {
          "UnitID": "11111111",
          "TypeCode": 25,
          "PracticeCode": 35,
          "InsuredShare": 1.0,
          "SaleDate": "20180315"
        }
      ],
      "Intervals": [
        {
          "IntervalStartDate": "20171101",
          "IntervalEndDate": "20171130"
        }
      ]
    }
  ]
}

When I call the web API with a POST (httr package) using R as below, the Sample1.txt file contains the above JSON.

myjson <- read_file("C:\\Testing\\Sample1.txt")
# JSON encoded
url1 <- "http://localhost:49688/API/ComputeFR"
 postresult <- POST(url1, body = myjson, verbose())
output <- content(postresult)

verbose() in R generates the following:

-> POST /API/ComputeFR HTTP/1.1
-> Host: localhost:49688
-> User-Agent: libcurl/7.53.1 r-curl/2.4 httr/1.3.1
-> Accept-Encoding: gzip, deflate
-> Accept: application/json, text/xml, application/xml, */*
-> Content-Length: 831
-> 
>> {
>>   "UserId": "test",
>>   "pwd": "test123",
>>   "ContractParam": [
>>     {
>>       "ContractID": "00000",
>>       "Units": [
>>         {
>>           "UnitID": "11111111",
>>           "TypeCode": 25,
>>           "PracticeCode": 35,
>>           "InsuredShare": 1.0,
>>           "SaleDate": "20180315"
>>         }
>>       ],
>>       "Intervals": [
>>         {
>>           "IntervalStartDate": "20171101",
>>           "IntervalEndDate": "20171130"
>>         }
>>       ]
>>     }
>>   ]
>> }

The Web API then returns the following:

<- HTTP/1.1 404 Incoming contract info is NULL
<- Cache-Control: no-cache
<- Pragma: no-cache
<- Content-Length: 17
<- Content-Type: text/plain; charset=utf-8
<- Expires: -1
<- Server: Microsoft-IIS/10.0
<- X-AspNet-Version: 4.0.30319
<- X-SourceFiles: =?UTF-8?B?QzpcQ3JvcENvZGVcRmxleFJhdGVXZWJBcGlcRmxleFJhdGVXZWJBcGlcYXBpXEZsZXhSYXRl?=
<- X-Powered-By: ASP.NET
<- Date: Wed, 10 Jan 2018 15:28:41 GMT

The web API receives the request (I can see the headers and the content length equal what is sent from the R call). However the model is always null.

Can someone please help me understand the issue and suggest a solution for this. Thank you very much for your time and help.

Try setting the Content-Type header to "application/json" in your R request. PostAsJsonAsync is likely doing this for you in your C# client. Content-Type tells the endpoint what kind of data you're sending. Accept says what you expect in response.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM