学习WebApi时间较短,在一个项目中需要向WebApi发送数据,但是使用C#调用WebApi(Post)时总返回400错误,找了很久,总以为是调用方法有问题,后来发现其实是WebApi中,Post方法参数的问题。下面是测试代码:
实体:
public class Standard
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public string Hobby { get; set; }
}
方法:
private void Send()
{
Standard s = new Standard
{
Name = "tt",
Age = 24,
Hobby = "test",
Gender = "1"
};
string json = JsonConvert.SerializeObject(s);
string url = "http://localhost:2374/api/values";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.Method = "POST";
request.ContentType = "application/json";
try
{
//GET方法没有写入流这一部分
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(json);
}
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
response = (HttpWebResponse)e.Response;
}
}
catch(Exception e)
{
throw e;
}
}
WebApi:
[HttpPost]
public async Task Post([FromBody] Standard value)
{
//……
}
WebApi这里要注意两点:
1、参数需要加[FromBody]帽子,不然取不到值;
2、因为发送方法,发送的是一个经过json序列化的实体,所以Post方法的参数也必须是对应的实体,Post方法在接收到值时,会自动按参数类型反序列化。我之前这个参数写的是string
类型,每次调用都返回400错误,提示解析时遇到意外字符,即“{”。
一个小错误,但是之前找了很久都没有人提,这里写个博客记录一下。