• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Asp.netWebApi调用

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

一、创建新的控制器Users,并且给控制器添加模型User,代码如下:

 

声明:路由配置是webapi默认的设置遵循Restfull风格:

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

 

(1)模型类代码

    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }

    }

(2)控制器代码

public class UsersController : ApiController
    {
        private List<User> list = new List<User>()
        {
            new User(){Gender="woman",Id=1,Name="M`r Li"},
            new User(){Gender="woman",Id=2,Name="M`r Huang"},
            new User(){Gender="woman",Id=3,Name="M`r He"},
            new User(){Gender="woman",Id=4,Name="Miss Liu"},
            new User(){Gender="woman",Id=5,Name="M`r Zhang"},
            new User(){Gender="woman",Id=6,Name="M`r Yao"},
            new User(){Gender="woman",Id=7,Name="M`r Wu"}
        };
        // GET: api/Users
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Users/5
        public string Get(int id)
        {
            return "value";
        }


        [HttpPost]
        public IEnumerable<User> Post(User user)
        {
            return list.Where<User>(u => u.Id == user.Id);
        }

        [Route("api/Users/id")]
        [HttpPost]
        public IEnumerable<User> PostById(JObject id)
        {
            var _jlist =  id.Properties().ToList();
            int _id = int.Parse(_jlist[0].Value.ToString());
            return list.Where<User>(u => u.Id >= _id);
        }

        [Route("api/Users/name")]
        [HttpPost]
        public IEnumerable<User> PostByName(JObject name)
        {
            var _nlist = name.Properties().ToList();
            string _name = _nlist[0].Value.ToString();
            return list.Where(u => u.Name == _name);
        }
    }

二、api的前端调用

A、使用JQuery发起ajax请求调用WebApi

$(function () {

        //发起get请求--------->对应 api 为 Get()
        // 调用结果 :["value1", "value2"]
        $.get("https://localhost:44320/api/Users", {}, function (ret) {
            console.log(ret,"11111");
        });

        //发起post请求------------>对应api 为 Post(User user)
        // 调用结果 : {Id: 3, Name: "M`r He", Gender: "woman"}
        let data = { Id: 3, Name: 'M`r Li', Gender: 'woman' };
        $.post("https://localhost:44320/api/Users", data, function (ret) {
            console.log(ret, "22222");
        });

        {
            //发起post请求------------>对应api 为 PostById(JObject id)
            // 调用结果 : 
            //{ Id: 1, Name: "M`r Li", Gender: "woman" }
            //{ Id: 2, Name: "M`r Huang", Gender: "woman" }
            //{ Id: 3, Name: "M`r He", Gender: "woman" }
            //{ Id: 4, Name: "Miss Liu", Gender: "woman" }
            //{ Id: 5, Name: "M`r Zhang", Gender: "woman" }
            //{ Id: 6, Name: "M`r Yao", Gender: "woman" }
            //{ Id: 7, Name: "M`r Wu", Gender: "woman" }
            let data = { id: 1 };
            $.post("https://localhost:44320/api/Users/id", data, function (ret) {
                console.log(ret, "33333");
            });
        }

        {
            //发起post请求------------>对应api 为 PostByName(JObject name)
            //调用结果 : {Id: 2, Name: "M`r Huang", Gender: "woman"}
            let data = { name: 'M`r Huang' };
            $.post("https://localhost:44320/api/Users/name", data, function (ret) {
                console.log(ret, "44444");
            });
        }

            //发起post请求------------>对应api 为 Post(User user)
            //调用结果 : {Id: 1, Name: "M`r Li", Gender: "woman"}
        $.ajax({
            type: "post",
            url: "https://localhost:44320/api/Users",
            data: { Id: 1, Name: 'M`r Li', Gender: 'woman' },
            success: function (data, status) {
                if (status == "success") {
                    console.log(data, "55555");
                }
            }
        });
    })

 

B、使用Vue-Resource调用,代码如下:

1、前端涉及到的代码:

<script src="~/Scripts/vue2.6.12.js"></script>
<script src="~/Scripts/vue-resoueces1.5.1.js"></script>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<div id="app">
    get-api/Users <input type="button" name="name" value="getone" />
    get-api/Users <input type="button" name="name" value="gettwo" />
    post-api/Users <input type="button" name="name" value="api/Users" v-on:click="postone" />
    post-api/Users/id <input type="button" name="name" value="api/Users" v-on:click="posttwo" />
    post-api/Users/name <input type="button" name="name" value="api/Users" v-on:click="postthree" />
    <div>
        <table class="table table-bordered table-hover table-striped">
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Gender</th>
            </tr>
            <tbody>
                <tr v-for="(user,index) in users" :key="index">
                    <td>{{user.Id}}</td>
                    <td>{{user.Name}}</td>
                    <td>{{user.Gender}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

2、vue的代码如下:

<script>
   //创建vue实例
    var vm = new Vue({
        el: "#app",
        data: {
            users: [1, 2, 3]
        },
     //页面点击时触发这些调用webapi的函数
     //调用结果同上jQuery调用 methods: {
        //发起get请求 getone:
function () { this.$http.get("https://localhost:44320/api/Users", {}).then(result => { console.log(result); }) }, postone: function () { let data = { Id: 3, Name: 'M`r Li', Gender: 'woman' }; this.$http.post("https://localhost:44320/api/Users", data, {}).then(function (res) { console.log(res.body); }); }, posttwo: function () { let data = { id: 1 }; this.$http.post("https://localhost:44320/api/Users/id", data, {}).then(function (res) { console.log(res); console.log(this.users); this.users = res.body; console.log(this.users); }); }, postthree: function () { let data = { name: 'M`r Huang' }; this.$http.post("https://localhost:44320/api/Users/name", data, {}).then(function (res) { console.log(res); }); } } }); </script>

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
为ASP.NETMVC视图输出json发布时间:2022-07-10
下一篇:
ASP.NETMVC3调用分部视图-PartialView的几种方式(集)发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap