[英]ASP.NET Web API receives a null as parameter in POST when called from R
我使用 Visual Studio 2012 在 ASP.NET MVC 4 中创建了一个 Web API。我使用 POST 方法来接收用户/调用应用程序发送的数据。
[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());
...
当我使用HttpClient.PostAsJsonAsync
和以下代码测试 API 的 POST 时,
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;
...
Web API 接收 JSON,上面的model
不为空,它显示调用例程发送的 JSON。 发送的 JSON 如下所示:
{
"UserId": "test",
"pwd": "test123",
"ContractParam": [
{
"ContractID": "00000",
"Units": [
{
"UnitID": "11111111",
"TypeCode": 25,
"PracticeCode": 35,
"InsuredShare": 1.0,
"SaleDate": "20180315"
}
],
"Intervals": [
{
"IntervalStartDate": "20171101",
"IntervalEndDate": "20171130"
}
]
}
]
}
当我使用 R 调用带有 POST(httr 包)的 Web API 时,如下所示,Sample1.txt 文件包含上述 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)
R 中的verbose()
生成以下内容:
-> 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"
>> }
>> ]
>> }
>> ]
>> }
然后 Web API 返回以下内容:
<- 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
Web API 接收请求(我可以看到标头和内容长度等于从 R 调用发送的内容)。 但是, model
始终为空。
有人可以帮助我理解这个问题并为此提出解决方案。 非常感谢您的时间和帮助。
尝试在 R 请求中将Content-Type
标头设置为"application/json"
。 PostAsJsonAsync
可能会在您的 C# 客户端中为您执行此操作。 Content-Type
告诉端点您发送的数据Content-Type
。 Accept
表示您期望的响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.