C# 将JSON传递到Web.API可以使用Fiddler,但不能在代码中使用
我正在尝试将JSON传递给Web.API服务。当我设置为POST并在C# 将JSON传递到Web.API可以使用Fiddler,但不能在代码中使用,c#,json,asp.net-web-api,C#,Json,Asp.net Web Api,我正在尝试将JSON传递给Web.API服务。当我设置为POST并在[FromBody]参数中获取值时,发送与Fiddler配合得很好: Http/1.1 User-Agent: Fiddler content-type: application/json; charset=utf-8 Host: http://localhost:27701/api/myList Content-Length: 883 但当我使用此C代码发布JSON时,[FromBody]参数为空: HttpContent
[FromBody]
参数中获取值时,发送与Fiddler配合得很好:
Http/1.1
User-Agent: Fiddler
content-type: application/json; charset=utf-8
Host: http://localhost:27701/api/myList
Content-Length: 883
但当我使用此C代码发布JSON时,[FromBody]
参数为空:
HttpContent content = new StringContent(data);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:27701/api/");
HttpResponseMessage response = client.PostAsync("myList", content).Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsAsync<string>().Result;
s = result;
}
有一件事是,如果我没有在fiddler中字符串的两边都加上
,
(单引号),[FromBody]
参数是空的,但是如果我把它们放在C样本上,响应是500服务器错误。您还没有发布接收方法代码,但根据提供的数据,它应该是一个具有一个参数的方法,该参数是表示JSON的对象。在这种情况下,您根本不需要使用FromBody
属性
如果您选中此项,您可以在那里找到:
默认情况下,Web API使用以下规则绑定参数:
- 如果参数是“简单”类型,Web API将尝试从URI获取值。简单类型包括.NET基本类型(int,
bool、double等),加上时间跨度、日期时间、Guid、十进制,
和字符串,再加上任何具有可从 一串 - 对于复杂类型,Web API尝试使用媒体类型格式化程序从消息体读取值
public class Address
{
public int Id { get; set; }
public string State { get; set; }
public string City { get; set; }
}
public class RootObject
{
public int Id { get; set; }
public int Count { get; set; }
public string StartDate { get; set; } // Keeped as string for simplicity
public Address Address { get; set; }
}
然后是一个非常简单的方法,可以接收这样的JSON:
public RootObject Post(RootObject req)
{
return req;
}
然后我用Fiddler测试了这两个:
Method:
POST
Headers:
Content-Type: application/json
Request Body:
{"Id":0,"Count":0,"StartDate":"\\/Date(-62135596800000)\\/","Address":{"Id":0,"State":"test","City":"test"}}
和C#代码:
在这两种情况下,我都能够返回发送的对象
一些提示:
- 使用Fiddler发送JSON时,应不使用任何转义 请求正文。只需输入有效的JSON即可
- 在C#代码中,如果需要用JSON声明字符串变量,则
将需要使用转义。例如var json=“\'a\:\'b\”代码>或
var json=@“a”:“b”代码>。如果您从某处收到JSON 否则你就不需要什么都不做了
- 永远不要使用
字符来封装JSON“
Method:
POST
Headers:
Content-Type: application/json
Request Body:
{"Id":0,"Count":0,"StartDate":"\\/Date(-62135596800000)\\/","Address":{"Id":0,"State":"test","City":"test"}}
var data = "{\"Id\":0,\"Count\":0,\"StartDate\":\"\\/Date(-62135596800000)\\/\",\"Address\":{\"Id\":0,\"State\":\"test\",\"City\":\"test\"}}";
using (var client = new HttpClient())
{
HttpContent content = new StringContent(data);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response =
client.PostAsync("http://my.url", content).Result;
var result = response.Content.ReadAsStringAsync().Result;
}