标签:length get odi json var ati for 基础类型 sts
WebApi传递实体类型的参数,可以直接将实体序列化,然后写入请求流即可。public class UsersController : ApiController
{
private List<Users> _userList = new List<Users>() {
new Users{ UserID=1, UserName="冯宝宝", UserEmail="fbaobao@yydy.com"},
new Users{ UserID=2, UserName="王也", UserEmail="wangye@yydy.com"}
};
[HttpPost]
public IEnumerable<Users> WithStringParam([FromBody]string name)
{
return _userList;
}
[HttpPost]
public IEnumerable<Users> WithIntParam([FromBody]int id)
{
return _userList;
}
[HttpPost]
public IEnumerable<Users> Post(Users user)
{
return _userList;
}
[HttpGet]
public IEnumerable<Users> YieldGet()
{
foreach (var item in _userList)
{
yield return item;
}
}
}
public class Users
{
public int UserID { get; set; }
public string UserName { get; set; }
public string UserEmail { get; set; }
}
}
后端调用的代码:
{
//dynamic val = new { UserID = "1", UserName = "冯宝宝", UserEmail = "fengbaobao@yydy.com" };
//HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://localhost:51151/Api/Users/WithStringParam") as HttpWebRequest;
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://localhost:51151/Api/Users/WithIntParam") as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
{
//string strJson = JsonConvert.SerializeObject(val);
//byte[] data = Encoding.UTF8.GetBytes(strJson);
//dynamic strVal = new { name = "aaa" };
//string strJson = JsonConvert.SerializeObject(strVal);
}
//byte[] data = Encoding.UTF8.GetBytes($"\"冯宝宝\"");//string参数
byte[] data = Encoding.UTF8.GetBytes($"12");//int参数
Stream requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
try
{
using (var res = httpWebRequest.GetResponse() as HttpWebResponse)
{
if (res.StatusCode == HttpStatusCode.OK)
{
StreamReader streamReader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string result = streamReader.ReadToEnd();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
标签:length get odi json var ati for 基础类型 sts
原文地址:http://blog.51cto.com/3544640/2149320