zoukankan      html  css  js  c++  java
  • WebApi传参总动员(四)

    前文介绍了Form Data 形式传参,本文介绍json传参。

    WebApi及Model:

        public class ValuesController : ApiController
        {
            
            [HttpPost]
            public string GetData(string name,[FromBody]Woman woman)
            {
                return "我是" + name + ",我喜欢" + woman.Name;
            }
            [HttpPost]
            public string GetData(Woman woman)
            {
                return woman.Age + "" + woman.Name;
            }
    
        }
        public class Woman//放在此处仅仅为了演示方便
        {
            public string Name{get;set;}
            public string Age{get;set;}
            public List<DateTime> ExerciseTime { get; set; }
            public List<Son> Son { get; set; }
        }
        public class Son
        {
            public string Name{get;set;}
            public int Age{get;set;}
            public List<DateTime> EatTime { get; set; }
        }
    View Code

    1、js

            var woman = {
                Name: '刘亦菲',
                Age: 18,
                ExerciseTime: [new Date(), new Date("2015-11-2 15:00:00")],
                Son: [
                    {
                        Name: '欧巴555',
                        Age: 1,
                        EatTime: [new Date('2015-11-2 9:0:0'), new Date('2015-11-2 19:00:00')]
                    }
                ]
            };
            $(function () {
                $('#btn').click(function () {
                    $.ajax({
                        type: "post",
                        url: "http://localhost:7601/api/values/GetData?name=楼主",
                        contentType: "application/json",
                        data: JSON.stringify(woman),
                        success: function (r) {
                            alert(r);
                        }
                    });
                });
            });
    View Code

    执行结果:

    可以看到的是:较为复杂的值,都正确传递过来了。唯一特别的是时间,传递过来的是utc世界时间,落后北京时间8小时,需要ToLocalTime一下。

    2、客户端调用。我们采取HttpClient异步方式发起请求。

    来看包装的方法。

            public static async void AsyncPostApiRequest(string postUrl, string postJson, int seconds)
            {
                var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
                using (var http = new HttpClient(handler))
                {
                    http.Timeout = TimeSpan.FromSeconds(seconds);
                    var content = new StringContent(postJson);
                    //与jq的ajax方法中的contentType: "application/json"一样,告诉服务端发送过来的数据按json字符串处理
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    CancellationTokenSource cts = new CancellationTokenSource();
                    try
                    {
                        var response = await http.PostAsync(postUrl, content, cts.Token); //await异步等待回应
                        //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
                        {
                            string result = (await response.Content.ReadAsStringAsync());
                        }
                    }
                    catch (TaskCanceledException e)
                    {
                    }
                    catch (Exception ex)
                    {
                    }
                    // 调用Cancel方法取消网络请求
                    if (cts.Token.CanBeCanceled)
                    {
                        cts.Cancel();
                        cts.Dispose();
                        cts = null;
                    }
                }
            }
    View Code

    调用的方法:

            private void btnPost_Click(object sender, EventArgs e)
            {
                var women = new
                {
                    Name = "刘亦菲",
                    Age = 18,
                    ExerciseTime = new List<DateTime>() { 
                        DateTime.Now.Date.AddHours(13),
                        DateTime.Now.Date.AddHours(20)
                    },
                    Son =new object[]{ new {//因为匿名类的原因,此处不能用List,只能用object数组
                        Name = "欧巴555",
                        Age = 1,
                        EatTime = new List<DateTime>(){//此处是强类型,因此可以规范数据
                            DateTime.Now.Date.AddHours(9),
                            DateTime.Now.Date.AddHours(19)
                        }
                    }},
                };
                string postdata = JsonConvert.SerializeObject(women);
                string url = "http://localhost:7601/api/values/GetData?name=楼主";
                PostService.AsyncPostApiRequest(url, postdata, 20);
            }
    View Code

    结果:

    可以看到,数据被正确的传递进来了,而且时间是Local的。

    总结:json传参方法最为简单、直观、顺畅、灵活,建议WebApi传参用此方法。

    最复杂传参,以客户端代码为例,js差不多。

    WebApi:

            [HttpPost]
            public string GetData(string name, Woman woman,Son son)
            {
                return "我是" + name + ",我喜欢" + woman.Name+"我们有一个共同的孩子叫:"+son.Name+"每天第一次吃奶的时间:"+son.EatTime[0];
            }

    预想的结果:name、woman、son均可以自动获取各自正确的值。

    客户端代码:

            private void btnPost_Click(object sender, EventArgs e)
            {
                var women = new
                {
                    Name = "刘亦菲",
                    Age = 18,
                    ExerciseTime = new List<DateTime>() { 
                        DateTime.Now.Date.AddHours(13),
                        DateTime.Now.Date.AddHours(20)
                    },
                    Son =new object[]{ new {//因为匿名类的原因,此处不能用List,只能用object数组
                        Name = "欧巴555",
                        Age = 1,
                        EatTime = new List<DateTime>(){//此处是强类型,因此可以规范数据
                            DateTime.Now.Date.AddHours(9),
                            DateTime.Now.Date.AddHours(19)
                        }
                    }},
                };
                var son = new {
                    Name = "楼菲子",
                    Age = 1,
                    EatTime = new List<DateTime>(){//此处是强类型,因此可以规范数据
                            DateTime.Now.Date.AddHours(7),
                            DateTime.Now.Date.AddHours(19)
                        }
    
                };
                string postdata = JsonConvert.SerializeObject(new { women=women,son=son});
                string url = "http://localhost:7601/api/values/GetData?name=楼主";
                PostService.AsyncPostApiRequest(url, postdata, 20);
            }
    View Code

    然而这没什么乱用:

    这就引出最后一种最复杂类型的传参,我们下回分解。

  • 相关阅读:
    FIREDAC操作SQLITE内存数据库
    DELPHI移动端支付宝支付
    DELPHI支付宝支付代码
    DELPHI微信支付代码
    mssql内存表
    Ubuntu下添加开机启动项的2种方法
    docker容器中安装vim
    使用find命令查找Linux中的隐藏文件的方法
    Go语言_RPC_Go语言的RPC
    Mac下export生效
  • 原文地址:https://www.cnblogs.com/luhuanong/p/4930275.html
Copyright © 2011-2022 走看看