您好,登錄后才能下訂單哦!
WebApi傳遞實體類型的參數,可以直接將實體序列化,然后寫入請求流即可。
傳遞基礎類型的參數卻不這么方便。以下是自己踩過的坑,分享出來給大家。調用的方式是通過后端,前端的沒有總結。
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);
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。