C# 后台调用webApi

public static string HttpPost(string url,string body)
{
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Accept = "text/html, application/xhtml+xml,*/*";
request.ContentType = "application/json";

byte[] buffer = encoding.GetBytes(body);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using(StreamReader reader=new StreamReader(response.GetResponseStream(),Encoding.UTF8))
{
return reader.ReadToEnd();
}
}

//调用

protected void Button1_Click(object sender, EventArgs e)
{
int c = Convert.ToInt32(TextBox1.Text.ToString());
int d = Convert.ToInt32(TextBox2.Text.ToString());
var json=new{a=c,b=d};
string strjson=JsonConvert.SerializeObject(json);
string result = HttpPost("http://localhost:44510/api/Values", strjson);
TextBox3.Text = result;
}

调用的webapi post代码:

[HttpPost]
public int add(dynamic obj)
{
var a = Convert.ToInt32(obj.a);
var b = Convert.ToInt32(obj.b);
return Convert.ToInt32(a) + Convert.ToInt32(b);
}

此篇为多post多参数,之前出现了多次404错误,405错误,后看到 懒得安分 的关于webapi传参的博客解决了问题:

我也转载过来了:https://www.cnblogs.com/clj0102/p/9266479.html,里面有原博主地址

猜你喜欢

转载自www.cnblogs.com/clj0102/p/9266779.html