我使用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时,
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”不为null,它显示调用例程发送的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 Incomming 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调用发送的内容)。但是“模型”始终为空。
有人可以帮我理解这个问题并为此提出解决方案。非常感谢你的时间和帮助。
答案 0 :(得分:0)
尝试在R请求中将Content-Type标头设置为application / json。 PostAsJsonAsync可能会在您的c#客户端中为您执行此操作。 Content-Type告诉端点您要发送的数据类型。接受说出你的回应。