WEBAPI POST 传递多个参数时使用dynamic

 

 

 [HttpPost]
        // POST: api/EasyModelByRequestUrl
        public string Post(dynamic student)
        {


            return $"Post请求 姓名{student.name},性别{student.sex},年龄{student.age}";
        }

  

var student = new {name="张老三",sex="雄性",age=29 };


            Byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(student));
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:9892/api/EasyModelByRequestUrl");
            request.Method = "POST";

            request.ContentType = "application/json;charset=utf-8";
            request.ContentLength = bytes.Length;




            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader=new StreamReader( response.GetResponseStream()))
            {
                string result=reader.ReadToEnd();
                this.textBox1.Text = result;
            }

  

同样 我们也可以传递复杂对象

 

var adress = new { country="中国", province="江苏",city="淮安",county="涟水" };

var student = new {name="张老三",sex="雄性",age=29,adress= adress };

 

posted @ 2021-11-01 16:28  zq爱生活爱代码  阅读(217)  评论(0编辑  收藏  举报