zoukankan      html  css  js  c++  java
  • web api 初体验之 GET和POST传参

    上一篇我们讲到了web api跨域的问题 它几乎是每一个用web api的人都需要去解决的问题,不然都没法测试。接下来会遇到的问题就是传参了。还是用js前台调用服务的方式。

    GET 方式

    get方式传参 我们一般用于获取数据做条件筛选,也就是 “查”

    1.无参

    var look = function () {
            $.ajax({
                type: "GET",
                url: "http://172.28.20.106:8002/api/products/",
                dataType: "xml",
                contentType: 'application/xml;charset=gb2312;'
            }).success(function (res) {
                console.log(res);
            }).error(function (xhr, status) {
                console.log(xhr);
            });
        }

    2.一个参数

    var look = function () {
            $.ajax({
                type: "GET",
                url: "http://172.28.20.106:8002/api/users/",
               data:{"id":2},
                dataType: "xml",
                contentType: 'application/xml;charset=gb2312;'
            }).success(function (res) {
                console.log(res);
            }).error(function (xhr, status) {
                console.log(xhr);
            });
        }
    后台控制器方法如下:
      // GET api/users/5
            public string Get(int id)
            {
                return "id:"+id;
            }
    
    

    当然,也可以这样 把参数放在url

       var look = function () {
            $.ajax({
                type: "GET",
                url: "http://172.28.20.106:8002/api/users/2",
                dataType: "xml",
                contentType: 'application/xml;charset=gb2312;'
            }).success(function (res) {
                console.log(res);
            }).error(function (xhr, status) {
                console.log(xhr);
            });
        }

    输出:<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">id:2</string>

    3.多个简单参数

    后台方法体如下:
     // GET api/users/5
            public string Get(int id,string name)
            {
                return "id:" + id+" name:"+name;
            }
    
    

     多个参数时也比较简单 指明参数就行了

       var look = function () {
            $.ajax({
                type: "GET",
                url: "http://172.28.20.106:8002/api/users",
                data:{"id":2,"name":"张飞"},
                dataType: "json",
                contentType: 'application/json;charset=gb2312;'
            }).success(function (res) {
                console.log(res);
            }).error(function (xhr, status) {
                console.log(xhr);
            });
        }
    输出:"id:1 name:张飞"
    4.传递一个对象
    后台方法如下:
           [Route("Manger")]
            public string Get( Product model)
            {
                return "id:" + model.Id + " name:" + model.Name;
            }
    
    

    大家可能注意到这个方法上面有个标记了,这个其实是自定义路由,针对重载方法,防止出现匹配到多个适配的方法而报错




    这里必须要着重说明下,传递对象并不是理所当然的构造一个对象传过去就可以了
    var look = function () {
            var Product = {
                Id: 1,
                Name: "张飞",
                Category:"212",
                Price:22
            };
            $.ajax({
                type: "GET",
                url: "http://172.28.20.106:8002/api/users/Manger",
                //data:{ "model":{"Id":2,"Name":"张飞","Category":"22","Price":22}},
                data: Product ,
                dataType: "json",
                contentType: 'application/json;charset=gb2312;'
            }).success(function (res) {
                console.log(res);
            }).error(function (xhr, status) {
                console.log(xhr);
            });
        }
    这2种情况都会报错
    经过多次试验发现,后台方法参数列表内加入
    [FromUri]关键字就可以了
    加入后的方法如下
    [Route("Manger")]
    public string Get([FromUri] Product model)
    {
    return "id:" + model.Id + " name:" + model.Name;
    }

    输出:"id:1 name:张飞"

    POST方式

       post方式我们一般用来做增 删 改 ,不过在web api中post仅仅用来做增加操作  修改用put 删除用delete

    可以看看模板给我们生成的东西

           // PUT api/users/5
            public string Put(int id, [FromBody]string value)
            {
                return "id:" + id + "value:" + value;
            }
    
            // DELETE api/users/5
            public void Delete(int id)
            {
            }

    1.post的一个参数

    注意:post 提交必须使用

    [FromBody]关键字,并且参数列表里面只能有一个关键字,多个无效
    
    
    
     // POST api/users
              [Route("addid")]
            public string Post([FromBody]string value)
            {
                return "值是:" + value;
            }

    惯性思维,然后我们的前台会写成这个样子

            $.ajax({
                type: "POST",
                url: "http://172.28.20.106:8002/api/users/addid",
                data: {"value":"1"}
            }).success(function (res) {
                console.log(res);
            }).error(function (xhr, status) {
                console.log(xhr);
            });

    结果输出却发现   值是:"

    后台并没有收到数据

    总结:

      当只有一个参数时,有2种方式是可以获取到值的

     1. data: {"":"1"}  //忽略参数名
     2. data: "=1"   //加上”=“号 并且去掉花括号
         $.ajax({
                type: "POST",
                url: "http://172.28.20.106:8002/api/users/addid",
                data: {"":"1"}
            }).success(function (res) {
                console.log(res);
            }).error(function (xhr, status) {
                console.log(xhr);
            });
        $.ajax({
                type: "POST",
                url: "http://172.28.20.106:8002/api/users/addid",
                data: "=1"
            }).success(function (res) {
                console.log(res);
            }).error(function (xhr, status) {
                console.log(xhr);
            });

    输出:"值是:1"

    2.post的多个参数(1个对象)

       注意:post并不能提交多个参数,只能合并成对象

      错误写法

     public string Post(int id,string name)
              {
                  return "id是:" + id+" name:"+name;
              }

      public string Post(int id,[FromBody] string name)
              {
                  return "id是:" + id+" name:"+name;
              }
    
    

    正确写法:

     [Route("addmodel")]
    public string Post([FromBody] Product value) { return "值是:" + value.Id+" name :"+value.Name; }

    前台调用:

         var Product = {
                Id: 1,
                Name: "张飞",
                Category: "212",
                Price: 22
               
            };
            $.ajax({
                type: "POST",
                url: "http://172.28.20.106:8002/api/users/addmodel",
                data: Product
            }).success(function (res) {
                console.log(res);
            }).error(function (xhr, status) {
                console.log(xhr);
            });

    输出:  "值是:1 name :张飞"

    3.post的多个参数(多个对象)

        如果有多个对象,那就只能把它封装在一个扩展对象里面了

       

    public class User
        {
            public int ID { get; set; }
            public int Name { get; set; }
        }
    
    public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Category { get; set; }
            public decimal Price { get; set; }
        }
    
    //实体扩展类
      public class NewProduct
        {
            public User user { get; set; }
            public Product product { get; set; }
        }

    接下来就以扩展类为参数,后台代码变成这样

             [Route("addnewmodel")]
              public string Post([FromBody] NewProduct value)
              {
                  return "userid值是:" + value.user.ID + " priduct值是 :" + value.product.Name;
              }

    接下来就是前台调用

        var Product = {
                Id: 1,
                Name: "手机",
                Category: "212",
                Price: 22
               
            };
            var User = {
                Id: 1,
                Name: "张飞",
            };
            $.ajax({
                type: "POST",
                url: "http://172.28.20.106:8002/api/users/addnewmodel",
                data: { Product: Product ,User:User}
            }).success(function (res) {
                console.log(res);
            }).error(function (xhr, status) {
                console.log(xhr);
            });

    输出: "userid值是:1 priduct值是 :手机"

    也可以写成这样

     $.ajax({
                type: "POST",
                url: "http://172.28.20.106:8002/api/users/addnewmodel",
                data: {
                    Product: { Id: 1, Name: "手机", Category: "212", Price: 22 }, User: { Id: 1, Name: "张飞", }
                }
            }).success(function (res) {
                console.log(res);
            }).error(function (xhr, status) {
                console.log(xhr);
            });

    自定义路由

    额外的提一下,由于我代码中大量用到它,还是介绍一下
    使用场景:用于方法重载 忽略方法名 自定义url(更好看点)

    使用步骤:
    1.在控制器类上方加入一个标记
       [RoutePrefix("api/users")]
        public class UsersController : ApiController
        {
        }

    里面的内容可以根据自己的喜好来定义

    2.在方法中加入路由标记[Route("Manger")]

          [Route("Manger")]
            public string Get([FromUri] Product model)
            {
                return "id:" + model.Id + " name:" + model.Name+" price:"+model.Price;
            }

    这样再访问时就可以使用

    api/users/Manger  

    注意:如果想实现第2步,必须先实现第一步,不然会报错

    总结

      传参的方式估计不只这几种,目前只用到了这些。后续如果继续深入学习 也会分享给大家。如果有理解错误的地方,欢迎指正。避免误人子弟! 如果觉得有收获,请关注 推荐 http://www.cnblogs.com/jingch个人主页

  • 相关阅读:
    67. Add Binary
    66. Plus One
    64. Minimum Path Sum
    63. Unique Paths II
    How to skip all the wizard pages and go directly to the installation process?
    Inno Setup打包之先卸载再安装
    How to change the header background color of a QTableView
    Openstack object list 一次最多有一万个 object
    Openstack 的 Log 在 /var/log/syslog 里 【Ubuntu】
    Git 分支
  • 原文地址:https://www.cnblogs.com/jingch/p/4866462.html
Copyright © 2011-2022 走看看