public class TestController : ApiController
{
//发起请求
[HttpGet]
public async TaskGet()
{//调用请求方法
var q = await APIPost("http://localhost:16727/api/Test/Post","{'name':'Hello','age':17}");
//post api的返回数据
return q;
}
//被请求的post api
[HttpPost]
public string Post(User data)
{
return "123";
}
//传递对象
public class User
{
public string name{get;set;}
public int age{get;set;}
}
public static async TaskAPIPost(string url, string data)
{
string result = string.Empty;
//设置HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
//创建HttpClient(注意传入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(new Dictionary()
{
{"", data}//键名必须为空
});
//await异步等待回应
var response = await http.PostAsync(url, content);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode();
//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
result = await response.Content.ReadAsStringAsync();
}
return result;
}
}
你自己测试一下把。没问题的
public class TestController : ApiController
{
//发起请求
[HttpGet]
public async TaskGet()
{//调用请求方法
var q = await APIPost("http://localhost:16727/api/Test/Post","{'name':'Hello','age':17}");
//post api的返回数据
return q;
}
//被请求的post api
[HttpPost]
public string Post(User data)
{
return "123";
}
//传递对象
public class User
{
public string name{get;set;}
public int age{get;set;}
}
public static async TaskAPIPost(string url, string data)
{
string result = string.Empty;
//设置HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
//创建HttpClient(注意传入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(new Dictionary()
{
{"", data}//键名必须为空
});
//await异步等待回应
var response = await http.PostAsync(url, content);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode();
//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
result = await response.Content.ReadAsStringAsync();
}
return result;
}
}
也许和请求头的内容类型有关系 ,WEBAPI接收POST来的参数时,可以建一个实体类作参数类型放在方法参数上
request.ContentType = "application/x-www-form-urlencoded" // "表单"形式
"application/json";
"text/xml";
我晕 我说的是我api接收不到实体参数 不是客户端接收不到返回值
你在Post方法里面打断点看看参数data的值有吗 我刚才按照你这个参数格式写还是接收不到
传递对象的话,使用以下方式
var content = new FormUrlEncodedContent(new Dictionary()
{
{"name","hello"},
{"age","16"}
});
public class BaseParameter
{
public int Property { get; set; }
}
public class Parameter : BaseParameter
{
public new Guid Property { get; set; }
}