Asp.net WebApi调用

一、创建新的控制器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>
原文地址:https://www.cnblogs.com/yuanshuang-club/p/13649783.html