HttpWebRequest Post请求webapi

1、WebApi设置成Post请求
在方法名加特性[HttpPost]或者方法名以Post开头
如下截图:

2、使用(服务端要与客户端对应起来)
【单一字符串方式】:
注意:ContentType = "application/x-www-form-urlencoded";
格式一:

客户端参数格式:如 "=abc123"或者{'':abc123}

        [HttpPost]
        public string PostHello([FromBody] string str)
        {
            return "Hello," + str;
        }

格式二:

客户端参数格式: url地址加上Values 如:"http://localhost:21235/api/Products/PostTest?str=abc123"

        public string PostTest(string str) 
        {
            return str;
        }

格式三:

客户端参数格式:// 如:"Name=MrBlack"

        public string PostTest2()
        {
            string name = HttpContext.Current.Request.Form["Name"].ToString();          
            return name ;
        }

【实体类作为参数】(json格式或Dictionary)

注意:request.ContentType = "application/json; charset=utf-8 ";

客户端参数:如 {"Id":"9527","Name":"zhangSan","Category":"A8","Price":"88"}
或者Id=9527&Name=zhangSan&Category=A8&Price=88

格式一:

        public HttpResponseMessage PostProduct([FromBody] Product product)
        {
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent("{"name":"hello"}", Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }

格式二:

        [HttpPost]
        public object SaveData(dynamic obj)
        {
            var strName = Convert.ToString(obj.Name);
            return strName;
        }

格式三:

        [HttpPost]
        public string PostGetProduct(JObject product)
        {
            return JsonConvert.SerializeObject(product);
        }

 最好加上几个常见的请求方法:

        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, */*";
            //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();
            }
        }  
public static string HttpPost(string url, IDictionary<string, string> dic)
        {
            HttpWebRequest request = null;
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            //POST参数拼接     
            if (!(dic == null || dic.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in dic.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, dic[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, dic[key]);
                    }
                    i++;
                }
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
原文地址:https://www.cnblogs.com/MrBlackJ/p/8891702.html