zoukankan      html  css  js  c++  java
  • WebAPI传参

    1.GET请求传递参数

    URL传参:http://localhost/ApiTest/test?id=1

    API接收参数

    [HttpGet]

    public string GetUser(int id) { return "User:" + id; }

    传递JSON对象:

    $.ajax({

    type: "get",

    url: "http://localhost/ApiTest/test",

    contentType: "application/json",

    data: { id: "1" },

    success: function (data, status) { if (status == "success") { $("#div_test").html(data); } }

    });

    API接收参数

    [HttpGet]

    public string GetUser([FromUri]UserDto obj) { return "User:" + obj.id; }

     如果你不想使用[FromUri]这些在参数里面加特性的这种“怪异”写法,也可以采用先序列化,再在后台反序列的方式。

    $.ajax({
    type: "get",
    url: "http://localhost:27221/api/Charging/GetByModel",
    contentType: "application/json",
    data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) },
    success: function (data, status) {
    if (status == "success") {
    $("#div_test").html(data);
    }
    }
    });

    [HttpGet]

    public string GetByModel(string strQuery)

    {

    TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery);

    return "ChargingData" + oData.ID;

    }

    注意:方法名以Get开头,WebApi会自动默认这个请求就是get请求,而如果你以其他名称开头而又不标注方法的请求方式,那么这个时候服务器虽然找到了这个方法,但是由于请求方式不确定,所以直接返回给你405——方法不被允许的错误。

    POST传参:

    单个参数:

    $.ajax({
    type: "post",
    url: "http://localhost:27221/api/Charging/SaveData",
    data: { "": "Jim" },
    success: function (data, status) {}
    });
    [HttpPost]
    public bool SaveData([FromBody]string NAME){return true;}

    多个参数,使用dynamic:

    $.ajax({
    type: "post",
    url: "http://localhost:27221/api/Charging/SaveData",
    contentType: 'application/json',
    data: JSON.stringify({ NAME: "Jim",DES:"备注" }),
    success: function (data, status) {}
    });
    [HttpPost]
    public object SaveData(dynamic obj){var strName = Convert.ToString(obj.NAME);return strName;}

    传递集合:

    var arr = [
    { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" },
    { ID: "2", NAME: "Lilei", CREATETIME: "1990-12-11" },
    { ID: "3", NAME: "Lucy", CREATETIME: "1986-01-10" }
    ];
    $.ajax({
    type: "post",
    url: "http://localhost:27221/api/Charging/SaveData",
    contentType: 'application/json',
    data: JSON.stringify(arr),
    success: function (data, status) {}
    });

    [HttpPost]
    public bool SaveData(List<TB_CHARGING> lstCharging)
    {
    return true;
    }

    来源:http://www.cnblogs.com/landeanfen/p/5337072.html

  • 相关阅读:
    【整理】PHP获取客户端真实IP地址详解
    配置百度编辑器变成纯代码编辑器
    Notepad++安装SVN插件
    【CodeBase】【转】php随机生成汉字
    【CodeBase】PHP打印所有用户自定义常量
    php5.3新垃圾回收机制详解
    php脚本cli 模式运行
    php 内存分配新
    php-fpm epoll封装
    火焰图定位dbproxy问题
  • 原文地址:https://www.cnblogs.com/xsj1989/p/7905409.html
Copyright © 2011-2022 走看看