asp.net web api

webapi簡介

在asp.net中,建立一個HTTP服務,有不少方案,之前用ashx,通常處理程序(HttpHandler),如今能夠用webapijavascript

微軟的web api是在vs2012上的mvc4項目綁定發行的,它提出的web api是徹底基於RESTful標準的,徹底不一樣於以前的(同是SOAP協議的)wcf和webService,它是簡單,代碼可讀性強的,上手快的,若是要拿它和web服務相比,我會說,它的接口更標準,更清晰,沒有混亂的方法名稱,有的只有幾種標準的請求,如get,post,put,delete等,它們分別對應的幾個操做,下面講一下:css

GET:獲取html

POST:添加java

PUT:修改jquery

DELETE:刪除web

注意上面公開的API接口都是在XMLHttpRequest狀況下調用的,固然你可使用jquery的ajax組件來完成這個請求調用,它的代碼更加面向對象,下面會舉例說明。ajax

WebAPI是根據請求頭信息(Accept Header)來查找已經格式化註冊的響應頭信息(Content-Type)來肯定它應該返回的輸出類型json/xml,瀏覽器訪問基本都是xml,若是隻須要json的話能夠經過Global.asax設置json

protected void Application_Start(object sender, EventArgs e)
      {//默認JSON
          GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
      }

 

webapi示例(CRUD)

環境:vs201五、iis七、webapi2.0、.net4.5.2api

功能:webapi+ajax實現增刪改查瀏覽器

模型

namespace cms.Model
{public partial class student
    {
        public int ID { get; set; }
        public string name { get; set; }
        public int sex { get; set; }
        public int age { get; set; }
        public System.DateTime timesAdd { get; set; }
    }
}

修改webapi路由

webapi默認路由api/{controller}/{id},若是不喜歡能夠修改成api/{controller}/{action}/{id},下邊是修改後的代碼

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

 Controller代碼

using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Http;
using cms.BLL;
using cms.Model;
namespace cms.Web.API
{
    public class StudentController : ApiController
    {
        public studentBLL bll = new studentBLL();
        // GET: /api/student/GetList
        public IEnumerable<student> GetList()
        {
            var list = bll.FindList();
            return list;
        }

        // GET: api/Student/Get/5
        public student Get(int id)
        {
            var model = bll.Find(id);
            if (model == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return model;
        }
        //添加方法1:若是要添加的字段和模型恰好匹配就用這個
        // POST: api/Student/Post
        public student Post([FromBody]student entity)
        {
            entity.timesAdd = DateTime.Now;
            return bll.Add(entity);

            //dynamic data = new { name = _name, age = _age };
            //return Json<dynamic>(data);
        }
        //添加方法2:若是要添加的字段和模型不匹配就用這個
        // POST: api/Student/PostAdd
        //注意:webapi post接受數據dynamic,ajax調用時也得把json格式化爲字符串才行
        public student PostAdd(dynamic obj)
        {
            student model = new student();
            model.name = obj.name;
            model.sex = obj.sex;
            model.age = obj.age;
            model.timesAdd = DateTime.Now;
            return bll.Add(model);
        }

        // PUT: api/Student/Put/5
        public void Put(int id, [FromBody]student entity)
        {
            student model = bll.Find(id);
            model.name = entity.name;
            model.sex = entity.sex;
            model.age = entity.age;
            if (!bll.Update(model))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

        // DELETE: api/Student/Delete/5
        public void Delete(int id)
        {
            if (!bll.Delete(id))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }
    }
}

html代碼

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>webapi教程</title>
    <script type="text/javascript" src="Scripts/jquery-1.8.2.js"></script>
    <style type="text/css">
        h2 {
            border-bottom: solid 1px #ccc;
            padding-bottom: 10px;
        }

        #box_list span {
            margin-right: 30px;
            width: 100px;
            display: inline-block;
        }

        .time {
            width: 200px !important;
        }
    </style>
</head>
<body>
    <h2>webapi create</h2>
    <div>
        <p><input type="hidden" id="iid" /></p>
        <p>姓名:<input type="text" id="name" /></p>
        <p>性別:<input type="text" id="sex" /></p>
        <p>年齡:<input type="text" id="age" /></p>
        <p><input type="button" id="btnAdd" value="添加" />
            <input type="button" id="btnAdd2" value="添加2" />
        <input type="button" id="btnEdit" value="修改" /></p>
    </div>

    <h2>webapi list</h2>
    <div id="box_list"></div>
    <div>
        <input type="button" id="btnDel" value="刪除" />
        <input type="button" id="btnView" value="查看" />
    </div>
    <div id="box_view"></div>
    <script type="text/javascript">
        $(function () {
            GetList();
            $("#btnAdd").click(function () {
                var _data = { name: $("#name").val(), sex: $("#sex").val(), age: $("#age").val() };
                $.ajax({
                    type: "post",
                    url: "/api/Student/Post",
                    data: _data,
                    dataType: "json",
                    success: function (data) {
                        alert("添加成功");
                        GetList();
                    },
                    error: function () {
                        alert("添加失敗");
                    }
                });
            })
            $("#btnAdd2").click(function () {
                var _data = JSON.stringify({ name: $("#name").val(), sex: $("#sex").val(), age: $("#age").val() });
                $.ajax({
                    type: "post",
                    url: "/api/Student/PostAdd",
                    data: _data,
                    dataType: "json",
                    contentType: 'application/json',
                    success: function (data) {
                        alert("添加成功");
                        GetList();
                    },
                    error: function () {
                        alert("添加失敗");
                    }
                });
            })
            $("#btnDel").click(function () {
                var _iid = $('input:radio[name=iid]:checked').val();;
                $.ajax({
                    type: "Delete",
                    url: "/api/Student/Delete/" + _iid,
                    success: function (data) {
                        alert("刪除成功");
                        $('input:radio[name=iid]:checked').parents("p").remove();
                    },
                    error: function () {
                        alert("刪除失敗");
                    }
                });
            })
            $("#btnView").click(function () {
                var _iid = $('input:radio[name=iid]:checked').val();;
                $.ajax({
                    type: "get",
                    url: "/api/Student/get/" + _iid,
                    dataType: "json",
                    success: function (data) {
                        name: $("#iid").val(data.ID);
                        name: $("#name").val(data.name);
                        sex: $("#sex").val(data.sex);
                        age: $("#age").val(data.age)
                    },
                    error: function () {
                        alert("獲取失敗");
                    }
                });
            })
            $("#btnEdit").click(function () {
                var _data = { name: $("#name").val(), sex: $("#sex").val(), age: $("#age").val() };
                $.ajax({
                    type: "put",
                    url: "/api/Student/Put/" + $("#iid").val(),
                    data: _data,
                    success: function (data) {
                        alert("修改爲功");
                        GetList();
                    },
                    error: function () {
                        alert("修改失敗");
                    }
                });
            })
        })
        function GetList()
        {
            $("#box_list").html("");
            $.ajax({
                type: "GET",
                url: "/api/student/GetList",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (i, item) {
                        $("#box_list").append("<p><span><input type='radio' name='iid' value='" + item.ID + "' />" + item.ID + "</span><span>" + item.name + "</span><span>" + item.sex + "</span><span>" + item.age + "</span><span class='time'>" + item.timesAdd + "</span></p>")
                    });
                }
            });
        }
    </script>
</body>
</html>
相關文章
相關標籤/搜索