十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
WebApi传递实体类型的参数,可以直接将实体序列化,然后写入请求流即可。
传递基础类型的参数却不这么方便。以下是自己踩过的坑,分享出来给大家。调用的方式是通过后端,前端的没有总结。
WebApi后端代码:
公司专注于为企业提供网站制作、做网站、微信公众号开发、成都商城网站开发,成都小程序开发,软件定制网站设计等一站式互联网企业服务。凭借多年丰富的经验,我们会仔细了解各客户的需求而做出多方面的分析、设计、整合,为客户设计出具风格及创意性的商业解决方案,创新互联更提供一系列网站制作和网站推广的服务。
public class UsersController : ApiController
{
private List _userList = new List() {
new Users{ UserID=1, UserName="冯宝宝", UserEmail="fbaobao@yydy.com"},
new Users{ UserID=2, UserName="王也", UserEmail="wangye@yydy.com"}
};
[HttpPost]
public IEnumerable WithStringParam([FromBody]string name)
{
return _userList;
}
[HttpPost]
public IEnumerable WithIntParam([FromBody]int id)
{
return _userList;
}
[HttpPost]
public IEnumerable Post(Users user)
{
return _userList;
}
[HttpGet]
public IEnumerable 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);
}
}