.net core 跨接口传入一个json对象
平时写api接口的时候,通常都是直接传入单一的参数,很少传入一个对象。今天做跨接口传入一个json的对象的时候才发现以前的传入方式好像不行了。抛出远程调用接口异常。
常用的跨接口传入方式是:
string Url = " http://要调用接口的ip/Api/App/Ex_JZ_jiZhan?Data=" +参数;
string strJson = new DownloadHelper().LoadData(Url);
public string LoadData(string url)
{
//创建请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//GET请求
request.Method = "GET";
request.ReadWriteTimeout = 5000;
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
//返回内容
string retString = myStreamReader.ReadToEnd();
return retString;
}
上面的方式已经传入不了一个json对象了,我百度了一下,在修修改改,最终搞定了。
远程调用api接口的客户端代码:
string url = "http://124.160.103.218:1111/Api/App/Ex_JZ_jiZhan"; string jsonContent = JsonConvert.SerializeObject(json字符); using (var client = new HttpClient()) { var Data = new StringContent(jsonContent, Encoding.UTF8, "application/json"); //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer"); string result = client.PostAsync(url, Data).Result.Content.ReadAsStringAsync().Result; }
api接口:
/// <summary> /// 站点异常消息推送 /// </summary> /// <param name="Data">json字符串</param> /// <returns></returns> [HttpPost("Ex_JZ_jiZhan")] public string Ex_JZ_jiZhan([FromBody] object Data) { var json=Data//接到json对象
//下面根据实际情况自己处理。 }
注意:
1,var Data = new StringContent(jsonContent, Encoding.UTF8, "application/json")中ContentType=“application/json”
2,客户端传入的参数Data要和api接口参数Data名字要一样。
3,接口方法中的参数一定要加上 [FromBody]