关于写这篇手记,纯碎是记录自己做的,关于WebApi 2 怎么获取 由客户端提交的JSON数据。有不足或更好的写法的,请在写在评论中。如果能有对您有一点帮助,我就觉得很高兴了。
因为不是基础教程,所以不会一步步写。如果您完全没API 的经验,那么可能会看不明白。
客户端:
//GET请求
/// <summary>
/// 后台发送GET请求
/// </summary>
/// <param name="url">服务器地址</param>
/// <param name="data">发送的数据</param>
/// <returns></returns>
public string HttpGet(string url, string data)
{
try
{
//创建Get请求
url = url + (data == "" ? "" : "?") + data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
//接受返回来的数据
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
string retString = streamReader.ReadToEnd();
streamReader.Close();
stream.Close();
response.Close();
return retString;
}
catch (Exception)
{
return "";
}
}
//POST 请求
public string HttpPost2(string url = "", int id = 0)
{
try
{
url = "http://localhost:3526/api/Product/GetProductByID2";
string data = "{\"id\":3,\"name\":\"李\",\"ename\":\"Allex\"}";
//创建post请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST"; //POST请求
//request.ContentType = "application/json;charset=UTF-8";
request.ContentType = "text/json;charset=UTF-8";
byte[] payload = Encoding.UTF8.GetBytes(data);
request.ContentLength = payload.Length;
//发送post的请求
Stream writer = request.GetRequestStream();
writer.Write(payload, 0, payload.Length);
writer.Close();
//接受返回来的数据
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
string value = reader.ReadToEnd();
reader.Close();
stream.Close();
response.Close();
return value;
}
catch (Exception ex)
{
string errorMsg = ex.Message;
return "";
}
}
WEB API2 :
//如果使用GET 请求,那么会报错,没匹配到方法哦
[HttpPost]
public IHttpActionResult GetProductByID2()
{
byte[] byts = new byte[HttpContext.Current.Request.InputStream.Length];
//byts = by;
HttpContext.Current.Request.InputStream.Read(byts, 0, byts.Length);
string req = System.Text.Encoding.UTF8.GetString(byts);
//HttpContext.Current.Request.InputStream.Read(byts, 0, byts.Length);
// string data = Request.get["data"].;
int id = 1;
var product = products.FirstOrDefault(m => m.ID == id);
if (product == null)
{
return NotFound();
}
else
{
return Json(product);
}
}
结果:
这单纯是一个硬编码,API 中有一个接口,通过ID ,获取产品的信息,以JSON数据返回(客户端请求需要设置 request.ContentType = "text/json;charset=UTF-8";)
图片二:看到由客户端提交的JSON数据
1.如果提交的是整个要保存的实体,那么直接反序列化,再通过EF 保存即可
2.如果提交的数据很多,但只有部分需要保存,那么将JSON 转为 Dictionary后,再获取所需数据
暂时先写到这里,之后再修改