WEBAPI 传递实体对象,数组,集合

WEBAPI 传递实体对象,数组,集合

 

 

传递实体对象,首先定义负责对象

public class  Student
    {
        public string name { get; set; }
        public string sex { get; set; }
        public string age { get; set; }
        public Adress adress { get; set; }
    }
    public class Adress
    {
        public string country { get; set; }
        public string province { get; set; }
        public string city { get; set; }
        public string county { get; set; }

        public override string ToString()
        {
            return $"地址是{country}{province}省{city}市{county}县"; ;
        }

请求

private void button1_Click(object sender, EventArgs e)
        {
             string str = "张三";

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

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


            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;
            }

        }

接收

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


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

  

上一篇:navicat for mysql 将结果导出到txt文件


下一篇:WebApi ActionFilterAttribute 执行顺序以及发生异常时的执行顺序