ASP.NET Web API 学习系列(一)创建与简单的增删改查

来源:互联网 发布:淘宝ar buy怎么使用 编辑:程序博客网 时间:2024/05/22 05:02

之前没接触过web api,最近项目正好要用到这个所以就了解了一下,本人是一个菜鸟,第一次写博客,写的也都是一些最基础的东西,有哪些地方写的不够好还请大家多多指点和补充,谢谢!

创建一个Web api 的程序,上图哈哈(VS2015)




程序创建之后,系统会默认创建如下文件:

具体web api路由配置今天先不多说,可以参考下 http://blog.csdn.net/WuLex/article/details/71621266?ref=myread


开始一些简单的操作

先创建一个用户类



创建一个控制器



public class UserController : ApiController
    {
        private static List<Users> _personLst = new List<Users>();


        List<Users> list = new List<Users>() {
            new Users(){ ID=1, Age=23, Birthday=Convert.ToDateTime("1977-05-30"), Name="小明", Sex="男"},
            new Users(){ ID=2, Age=55, Birthday=Convert.ToDateTime("1937-05-30"), Name="张三", Sex="男"},
            new Users(){ ID=3, Age=12, Birthday=Convert.ToDateTime("1987-05-30"), Name="李四", Sex="男"},
            new Users(){ ID=4, Age=18, Birthday=Convert.ToDateTime("1997-05-30"), Name="小花", Sex="女"},
        };    
        /// <summary>
        /// /api/Contact
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IEnumerable<Users> GetListAll()
        {
            return list;
        }


        /// <summary>
        /// /api/Contact/id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public Users GetContactByID(int id)
        {
            Users contact = list.FirstOrDefault<Users>(item => item.ID == id);
            if (contact == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return contact;
        }


        /// <summary>
        /// 根据性别查询
        /// /api/Contact?sex=女
        /// </summary>
        /// <param name="sex"></param>
        /// <returns></returns>
        [HttpGet]
        public IEnumerable<Users> GetListBySex(string sex)
        {
            return list.Where(item => item.Sex == sex);
        }
        [HttpDelete]
        public void DeleteProduct(int id)
        {
            list.RemoveAll(item => item.ID == id);
        }
        [HttpPost]
        public bool add(Users user)
        {
            list.Add(user);
            return true;
        }
    }


前端页面:




<!DOCTYPE html>


<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>About</title>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    @*<script type="text/javascript" src="/Scripts/jquery-1.7.1.min.js"></script>*@
    <script>
        $(document).ready(function () {
            $("#btnAll").click(function () {
                $.getJSON("/api/User", function (data) {
                    var html = "<ul>";
                    $(data).each(function (i, item) {
                        html += "<li>" + item.ID + ":" + item.Name + ":" + item.Sex + "</li>";
                    });
                    html += "</ul>";
                    $("#contactAll").html(html);
                });
            });




            $("#btnID").click(function () {
                var id = $("#txtID").val();
                $.getJSON("/api/User/" + id, function (data) {
                    var html = "<ul>";
                    $(data).each(function (i, item) {
                        html += "<li>" + item.ID + ":" + item.Name + ":" + item.Sex + "</li>";
                    });
                    html += "</ul>";
                    $("#contactID").html(html);
                });
            });


            $("#btnSex").click(function () {
                var sex = $("#ddlSex").val();
                $.getJSON("/api/User?sex=" + sex, function (data) {
                    var html = "<ul>";
                    $(data).each(function (i, item) {
                        html += "<li>" + item.ID + ":" + item.Name + ":" + item.Sex + "</li>";
                    });
                    html += "</ul>";
                    $("#contactSex").html(html);
                });
            });
            //添加
            $('#btnOK').bind('click', function () {
                //创建ajax请求,将数据发送到后台处理
                var postData = {
                    ID: '7',
                    Age: 7,
                    data: '1977-05-30',
                    Name: 'QeeFee',
                    Sex: '女'
                };
                $.ajax({
                    type: 'POST',
                    url: '/api/User/1',
                    
                    dataType: 'json',
                    success: function (data, textStatus) {
                        alert(data);
                    },
                    error: function (xmlHttpRequest, textStatus, errorThrown) {
                    }
                });
            });
            //删除
            $("#btnID2").click(function () {
                var inputId = $("#txtID2").val();
                $.ajax({
                    url: "/api/User/" + inputId,
                    type: "DELETE",
                    contentType: "application/json; charset=uft-8",
                    success: function (data) {
                        alert("Id为 " + inputId + " 的记录删除成功!");
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("请求失败,消息:" + textStatus + "  " + errorThrown);
                    }
                });
            });
        })
    </script>
</head>
<body>
    <p>
        <input type="button" name="btnOK" id="btnOK" value="发送POST请求" />
    </p>
    <p>
        <input type="button" id="btnAll" value="显示所有用户" />&nbsp;
    </p>
    <p>
        <input type="text" id="txtID" name="txtID" />
        <input type="button" id="btnID" value="输入ID查询" />&nbsp;
    </p>
    <p>
        <input type="text" id="txtID2" name="txtID" />
        <input type="button" id="btnID2" value="输入ID删除" />&nbsp;
    </p>
    <p>
        <select id="ddlSex" name="ddlSex">
            <option value="男">男</option>
            <option value="女">女</option>
        </select>
        <input type="button" id="btnSex" value="性别查询" />&nbsp;
    </p>
    <div id="contactAll">
    </div>
    <div id="contactID">
    </div>
    <div id="contactSex">
    </div>
</body>



简单的一个例子,希望在看这个例子的同时学习web api 的路由机制

原创粉丝点击