使用HttpWebRequest向webapi传递数据并接收

1.通过路由接收参数,一般直接通过Url拼接直接匹配路由对应参数

这个直接通过设置路由,然后Url的位置对应即可;

 

2.通过QueryString传递参数

一般常见于Get访问数据传参;

 

3.通过[FromBody]直接在形参接收数据

客户端代码:

private async void Btn_SendData_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TB_SendDataUrl.Text))
                return;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(TB_SendDataUrl.Text);
            //request.ContentType = "application/x-www-form-urlencoded";//post发送数据必须使用这个标头才能被webapi [frombody]接收
            request.ContentType = "application/json";   //如果用了newtonsoft json 转换数据,那么必须用此标头,否则服务器将无法解析数据
            request.Method = "post";

            //发送的数据
            List<Person> listP = new List<Person>();
            Person p1 = new Person { ID = 1, Name = "张三", Age = 27 };
            Person p2 = new Person { ID = 2, Name = "李四", Age = 25 };
            Person p3 = new Person { ID = 3, Name = "王五", Age = 28 };
            listP.Add(p1); listP.Add(p2); listP.Add(p3);


            byte[] byteArray;
            Person p = new Person { ID = 1, Name = "张三", Age = 27 };
            //byteArray = Encoding.UTF8.GetBytes(ParseToString(p));
            string data = await JsonConvert.SerializeObjectAsync(listP);//直接序列化比上一行代码 更方便
            byteArray = Encoding.UTF8.GetBytes(data);//对数据进行转码,可以将中文数据进行传输
            request.ContentLength = byteArray.Length;

            Stream reqStream = await request.GetRequestStreamAsync();
            reqStream.Write(byteArray,0,byteArray.Length);
            reqStream.Close();

            string responseFromServer = string.Empty;
            WebResponse response = await request.GetResponseAsync();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                responseFromServer = reader.ReadToEnd();
            }
            if(string.IsNullOrEmpty(responseFromServer))
            {
                TB_SendResponseData.Text = "NULL";
            }
            else
            {
                TB_SendResponseData.Text = responseFromServer;
                List<Person> resData = JsonConvert.DeserializeObject<List<Person>>(responseFromServer);
                
            }
            response.Close();
        }

这里注意如果使用Newtonsoft将传输数据转换成了json,需要将contenttype设置为"application/json",这里十分关键,如果不是这个表头,服务端将不能正确解析数据

服务端代码:

   [HttpPost]
        public List<Person> SendListData([FromBody] List<Person> listP)
        {

            return listP;
        }

 

 

4.通过 解析Request.Content  中的请求消息实体得到数据,这种一般是通过Post上传的数据

 [HttpPost]
        public async Task<List<Person>> SendListJsontData()
        {
            List<Person> data = await this.Request.Content.ReadAsAsync<List<Person>>();
            return data;
        }

由于Task是4.5以上框架引入的,也可以在4.5以下框架中写成非异步调用的方式:

[HttpPost]
        public string PostNewData()
        {
            var t = this.Request.Content.ReadAsStringAsync();
            string data = t.Result;
            return data;
        }

前台使用的代码(推荐):

public static string HttpPost(string url, string PostData)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            //这里只有使用var data = HttpContext.Current.Request.Form["Name"].ToString();才切换到表单
            //如果api使用Request.Content.ReadAsStringAsync();则无所谓切换
            request.ContentType = "application/x-www-form-urlencoded ";//根据服务端进行 切换
            //request.ContentType = "application/json; charset=utf-8 ";

            byte[] buffer = encoding.GetBytes(PostData);
            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();
            }
        }

主函数调用

static void Main(string[] args)
        {
       
string url = "http://localhost:50041/api/Home/PostNewData"; //string data = "Name="; //for (int i = 0; i < 1000; i++) //{ // data += Guid.NewGuid().ToString() + ";"; //} string data = "Id=9527&Name=zhangSan&Category=A8&Price=88"; string res = HttpPost(url, data); Console.WriteLine($"结果:{res}"); Console.ReadKey(); }

 

使用.Net内置的方法即可读到传输数据。

 

posted @ 2020-03-04 16:57  ZedFFF  阅读(1578)  评论(0编辑  收藏  举报