(1)新建一个ASP.NET MVC项目,取名为:MyMvcWebAPIDemo,项目类型选择WebAPI。

(2)在Models中新增一个类,取名为:Product,作为我们要测试的实体模型。

 
 
1
2
3
4
5
6
7
public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }

(3)在Controllers中新增一个控制器,并选择“空WebAPI”类型模板,取名为:ProductController。

(4)为了方便进行数据测试,这里定义一个静态的产品集合。当然,在实际应用中,我们可能会从数据库中读取数据集合,并对其进行增删查改及各种查询操作。

 
 
1
2
3
4
5
6
7
8
static List<Product> products = new List<Product>
        {
            new Product { Id = 1, Name = "Nokia Lumia 1520", Category = "移动电话", Price = 3500 },
            new Product { Id = 2, Name = "Lenovo Thinkpad T430S", Category = "便携式计算机", Price = 8000 },
            new Product { Id = 3, Name = "锤子手机", Category = "移动电话", Price = 3300 } ,
            new Product { Id = 4, Name = "Wii", Category = "电视游戏机", Price = 1000 },
            new Product { Id = 5, Name = "Xbox 360", Category = "电视游戏机", Price = 3200 }
        };

(5)定义一些方法,用于对产品集合的各种操作:

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
public class ProductController : ApiController
    {
        static List<Product> products = new List<Product>
        {
            new Product { Id = 1, Name = "Nokia Lumia 1520", Category = "移动电话", Price = 3500 },
            new Product { Id = 2, Name = "Lenovo Thinkpad T430S", Category = "便携式计算机", Price = 8000 },
            new Product { Id = 3, Name = "锤子手机", Category = "移动电话", Price = 3300 } ,
            new Product { Id = 4, Name = "Wii", Category = "电视游戏机", Price = 1000 },
            new Product { Id = 5, Name = "Xbox 360", Category = "电视游戏机", Price = 3200 }
        };
 
        /// <summary>
        /// GET
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Product> GetAllProducts()
        {
            return products.OrderBy(p => p.Id);
        }
 
        /// <summary>
        /// GET
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Product GetProductById(int id)
        {
            Product product = products.FirstOrDefault(p => p.Id == id);
            if (product == null)
            {
                var resp = new HttpResponseMessage(HttpStatusCode.NotFound);
                throw new HttpResponseException(resp);
            }
 
            return product;
        }
 
        /// <summary>
        /// GET
        /// </summary>
        /// <param name="productName">产品名</param>
        /// <returns></returns>
        public Product GetProductByName(string productName)
        {
            Product product = products.FirstOrDefault(p => p.Name.Contains(productName));
            if (product == null)
            {
                var resp = new HttpResponseMessage(HttpStatusCode.NotFound);
                throw new HttpResponseException(resp);
            }
 
            return product;
        }
 
        /// <summary>
        /// GET
        /// </summary>
        /// <param name="category">类型名称</param>
        /// <returns></returns>
        public IEnumerable<Product> GetAllProductsByCategory(string category)
        {
            if (category.Equals("--请选择--"))
            {
                return products;
            }
 
            IEnumerable<Product> productList = products.Where(
                p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));
            return productList.OrderBy(p => p.Id);
        }
 
        /// <summary>
        /// POST
        /// </summary>
        /// <returns></returns>
        public bool PostProduct(Product product)
        {
            int index = products.FindIndex(p => p.Name == product.Name);
            if (index != -1)
            {
                return false;
            }
            product.Id = products.Max(p => p.Id) + 1;
            products.Add(product);
            return true;
        }
 
        /// <summary>
        /// PUT
        /// </summary>
        /// <returns></returns>
        public bool PutProduct(int id, [FromBody]Product product)
        {
            int index = products.FindIndex(p => p.Id == id);
            if (index == -1)
            {
                return false;
            }
 
            products.RemoveAt(index);
            products.Add(product);
            return true;
        }
 
        /// <summary>
        /// DELETE
        /// </summary>
        /// <returns></returns>
        public bool DeleteProduct(int id)
        {
            Product product = products.FirstOrDefault(p => p.Id == id);
            if (product == null)
            {
                return false;
            }
 
            products.Remove(product);
            return true;
        }
    }

一般来说,Http的四种访问类型中,Get:一般用作查询,多次操作得到结果一致;Post:一般用于修改、添加多次重复操作得到结果不一致。Put:一般用于修改,多次操作得到结果一致。Delete:一般用于删除数据,多次操作得到结果一致。

现在,我们来看一下我们写的这些方法:

①用于GET方式获取的方法有:

GetAllProducts用于获取所有产品的集合;GetProductById用于返回指定Id的产品对象;

GetProductByName用户返回指定Name的产品对象;GetAllProductsByCategory则用户返回指定Category(种类)的产品集合;

②用于POST方式的方法有:

PostProduct用于增加一个产品信息;

③用于PUT方式的方法有:

PutProduct用于修改一个指定的产品信息;

④用于DELETE方式的方法有:

DeleteProduct用于删除一个选择的产品信息;

以上GET、POST、PUT、DELETE则构成了我们通过HTTP协议对资源的各种操作了。具体的代码,这里我就不过多赘述,相信大家都能看懂。

(6)此时,我们有了一个能工作的Web API了。该控制器上的每个方法都映射到一个URI,例如下表中所示的前三个方法所对应的URI:

Controller Method
控制器方法
URI
GetAllProducts /api/product
GetProductById /api/product/id
GetProductsByCategory /api/product/?category=category

客户端可以通过URI来访问我们的控制器已达到对资源的操作,那么,我们可以设计一个页面来发送AJAX请求来实践一下。

(7)在Views中的默认Home/Index这个页面中,加入以下代码:

 
 
 
 
 
 

XHTML

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
<link href="~/Content/themes/easyui/bootstrap/easyui.css" rel="stylesheet" />
<link href="~/Content/themes/easyui/icon.css" rel="stylesheet" />
<header>
    <div class="content-wrapper">
        <div class="float-left">
            <p class="site-title">
                <a href="~/">ASP.NET Web API</a>
            </p>
        </div>
    </div>
</header>
<div id="body">
    <section class="featured">
        <div class="content-wrapper">
            @*<hgroup class="title">
                <h1>欢迎使用 ASP.NET Web API!</h1>
                <h2>这是一个简单的WebAPI入门Demo.</h2>
            </hgroup>*@
            <p>
                <strong>搜索:</strong>
                ①产品类型:
                    <select id="productTypes" name="productTypes" style="width: 120px; height: 34px;">
                        <option value="-1">--请选择--</option>
                        <option value="0">移动电话</option>
                        <option value="1">便携式计算机</option>
                        <option value="2">电视游戏机</option>
                    </select>
                ②产品名称:<input id="productName" name="productName" type="text" />
                <input id="btnSearchByName" name="btnSearchByName" type="button" value="搜 索" />
                <input id="btnSearchAll" name="searchAll" type="button" value="全 部" />
            </p>
            <p>
                <strong>新增:</strong>
                <br />
                产品名称:<input id="newProductName" name="newProductName" type="text" />
                产品类型:<select id="newProductType" name="newProductType" style="width: 120px; height: 34px;">
                    <option value="-1">--请选择--</option>
                    <option value="0">移动电话</option>
                    <option value="1">便携式计算机</option>
                    <option value="2">电视游戏机</option>
                </select>
                <br />
                产品价格:<input id="newProductPrice" name="newProductPrice" type="text" />
                <input id="btnPostProduct" name="btnPostProduct" type="button" value="新 增" />
            </p>
        </div>
    </section>
    <section class="content-wrapper main-content clear-fix">
        <h3>下面是从WebAPI获取的数据集:</h3>
        <div id="result">
        </div>
        @*<ol class="round">
            <li class="one">
                <h5>开始使用</h5>
                ASP.NET Web API  是一个框架,您可以通过该框架轻松生成可访问
                多种客户端(包括浏览器和移动设备)的 HTTP 服务。ASP.NET Web API
                是一个用于在 .NET Framework 之上生成 REST 样式的应用程序的理想平台。
                <a href="http://go.microsoft.com/fwlink/?LinkId=245160">了解详细信息...</a>
            </li>
        </ol>*@
    </section>
</div>
<!-- jBox modal -->
<div id="myMsgModal" class="notshow">
</div>
<!-- jBox edit modal -->
<div id="myEditModal" class="notshow">
    <input id="hiddProductId" type="hidden" />
    <table width="100%">
        <tr>
            <td align="right">产品名称:</td>
            <td>
                <input id="editProductName" name="editProductName" type="text" /></td>
        </tr>
        <tr>
            <td align="right">产品类型:</td>
            <td>
                <select id="editProductType" name="editProductType" style="width: 120px; height: 34px;">
                    <option value="-1">--请选择--</option>
                    <option value="0">移动电话</option>
                    <option value="1">便携式计算机</option>
                    <option value="2">电视游戏机</option>
                </select>
            </td>
        </tr>
        <tr>
            <td align="right">产品价格:</td>
            <td>
                <input id="editProductPrice" name="editProductPrice" type="text" />
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <a id="btnPutProduct" href="#" class="easyui-linkbutton">确定</a>
                <a id="btnCloseModal" href="#" class="easyui-linkbutton">关闭</a>
            </td>
        </tr>
    </table>
</div>
@section scripts{
    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Content/themes/easyui/jquery.easyui.min.js"></script>
    <script src="~/Content/themes/easyui/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript">
        $(function () {
            initData();
            bindClick();
        });
 
        function initData() {
            $.getJSON("api/Product", function (data) {
                if (data != null) {
                    if ($("#resultList").length > 0) {
                        $("#resultList").remove();
                    }
 
                    var html = "<ol id='resultList' class='round'>";
                    $.each(data, function (key, value) {
                        html += "<li class='one'><h5>" + value.Name + "</h5>类型:" + value.Category
                            + " 价格:" + value.Price + "  | <a href='#' onclick='editProduct(" + value.Id + ")'>编辑</a><a href='#' onclick='deleteProduct(" + value.Id + ")'>删除</a></li>";
                    });
                    html += "</ol>";
                    $("#result").append(html);
                }
            });
        }
 
        function bindClick() {
            // 01.按产品类型搜索产品
            $("#productTypes").bind("change", function () {
                $.getJSON("api/Product", { category: $(this).find("option:selected").text() }, function (data) {
                    if (data != null) {
                        $("#resultList").remove();
                        var html = "<ol id='resultList' class='round'>";
                        $.each(data, function (key, value) {
                            html += "<li class='one'><h5>" + value.Name + "</h5>类型:" + value.Category
                                + " 价格:" + value.Price + "  | <a href='#' onclick='editProduct(" + value.Id + ")'>编辑</a><a href='#' onclick='deleteProduct(" + value.Id + ")'>删除</a></li>";
                        });
                        html += "</ol>";
                        $("#result").append(html);
                    }
                });
            });
            // 02.按产品名搜索产品
            $("#btnSearchByName").bind("click", function () {
                var searchName = $("#productName").val();
                if (searchName == "") {
                    showMsg("提示", "您还没有输入要搜索的产品名称");
                }
                $.getJSON("api/Product", { productName: searchName }, function (data) {
                    if (data != null) {
                        $("#resultList").remove();
                        var html = "<ol id='resultList' class='round'>";
                        html += "<li class='one'><h5>" + data.Name + "</h5>类型:" + data.Category
                                + " 价格:" + data.Price + "  | <a href='#' onclick='editProduct(" + data.Id + ")'>编辑</a><a href='#' onclick='deleteProduct(" + data.Id + ")'>删除</a></li>";
                        html += "</ol>";
                        $("#result").append(html);
                        clearText();
                    }
                });
            });
            // 03.搜索全部产品信息
            $("#btnSearchAll").bind("click", initData);
            // 04.新增一个产品信息
            $("#btnPostProduct").bind("click", function () {
                var productName = $("#newProductName").val();
                var productCategory = $("#newProductType").find("option:selected").text();
                var productPrice = $("#newProductPrice").val();
 
                if (productName == "") {
                    showMsg("提示", "请输入产品名称");
                }
                else if (productCategory == "" || productCategory == "--请选择--") {
                    showMsg("提示", "请选择产品类型");
                }
                else if (productPrice == "") {
                    showMsg("提示", "请输入产品价格");
                }
                else if (isNaN(productPrice)) {
                    showMsg("提示", "产品价格请输入数字类型");
                }
                else {
                    $.post("api/Product", {
                        Name: productName,
                        Category: productCategory,
                        Price: productPrice
                    }, function (data) {
                        if (data != null && data == true) {
                            initData();
                            clearText();
                            showMsg("提示", "添加新产品操作成功");
                        }
                        else {
                            showMsg("提示", "添加新产品操作失败");
                        }
                    });
                }
            });
            // 07.修改一个产品信息
            $("#btnPutProduct").bind("click", function () {
                var productId = $("#hiddProductId").val();
                $.ajax({
                    type: "PUT",
                    url: "/api/Product/" + productId,
                    data: {
                        Id: productId,
                        Name: $("#editProductName").val(),
                        Category: $("#editProductType").find("option:selected").text(),
                        Price: $("#editProductPrice").val()
                    },
                    success: function (data) {
                        if (data == true) {
                            initData();
                            $("#myEditModal").window("close");
                            showMsg("提示", "您已成功修改那玩意");
                        }
                        else {
                            showMsg("提示", "修改那玩意操作失败");
                        }
                    }
                });
            });
            // 关闭模态对话框
            $("#btnCloseModal").bind("click", function () {
                $("#myEditModal").window("close");
            });
        }
        // 05.编辑一个产品信息
        function editProduct(productId) {
            $.getJSON("api/Product", { id: productId }, function (data) {
                if (data != null) {
                    $("#hiddProductId").val(data.Id);
                    $("#editProductName").val(data.Name);
                    switch (data.Category) {
                        case "移动电话":
                            $("#editProductType").val("0");
                            break;
                        case "便携式计算机":
                            $("#editProductType").val("1");
                            break;
                        case "电视游戏机":
                            $("#editProductType").val("2");
                            break;
                    }
                    $("#editProductPrice").val(data.Price);
                }
            });
            $("#myEditModal").show();
            $("#myEditModal").window({
                title: "编辑产品信息",
                modal: true,
                collapsible: true,
                minimizable: false,
                maximizable: false,
                resizable: false,
                width: 500,
                height: 220
            });
        }
        // 06.删除一个产品信息
        function deleteProduct(productId) {
            $.messager.confirm("提示", "您确定要删除这玩意?", function (r) {
                if (r) {
                    $.ajax({
                        type: "DELETE",
                        url: "/api/Product/" + productId,
                        data: {},
                        success: function (data) {
                            if (data == true) {
                                initData();
                                showMsg("提示", "您已成功删除那玩意");
                            }
                            else {
                                showMsg("提示", "删除那玩意操作失败");
                            }
                        }
                    });
                }
            });
        }
 
        function showMsg(title, msg) {
            $.messager.alert(title, msg, "info");
        }
 
        function clearText() {
            $("input[type=text]").val("");
        }
    </script>
}

通过调试运行,可以看到以下页面效果,并可以看到,由于我们在页面中加入了获取产品列表的GET请求,于是产品信息被加载到了页面中:

其对应的JS语句为:可以看到,我们通过api/Product调用了API控制器中的GetAllProducts方法,获取了所有产品信息。

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$.getJSON("api/Product", function (data) {
                if (data != null) {
                    if ($("#resultList").length > 0) {
                        $("#resultList").remove();
                    }
 
                    var html = "<ol id='resultList' class='round'>";
                    $.each(data, function (key, value) {
                        html += "<li class='one'><h5>" + value.Name + "</h5>类型:" + value.Category
                            + " 价格:" + value.Price + "  | <a href='#' onclick='editProduct(" + value.Id + ")'>编辑</a><a href='#' onclick='deleteProduct(" + value.Id + ")'>删除</a></li>";
                    });
                    html += "</ol>";
                    $("#result").append(html);
                }
});

(8)下面我们可以来试试其他的API方法:

3.4 第一个RestClient客户端项目

有了我们上面的WebAPI项目的支持,我们可以在客户端(如:WindowsForm项目、Windows Phone项目等等)对WebAPI项目中的资源进行访问和操作,现在我们就来实现一个RestClient控制台项目模拟一个客户端对WebAPI发起HTTP访问请求。

(1)新建一个控制台项目,取名为:MyConsoleRestClientDemo。

(2)新建一个类,取名为:RestClient.cs。它封装了我们常用的HTTP操作,如GET、POST、PUT、DELETE方式。

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
public class RestClient
    {
        private string BaseUri;
        public RestClient(string baseUri)
        {
            this.BaseUri = baseUri;
        }
 
        #region Delete方式
        public string Delete(string data, string uri)
        {
            return CommonHttpRequest(data, uri, "DELETE");
        }
 
        public string Delete(string uri)
        {
            //Web访问对象64
            string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            myRequest.Method = "DELETE";
            // 获得接口返回值68
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //string ReturnXml = HttpUtility.UrlDecode(reader.ReadToEnd());
            string ReturnXml = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();
            return ReturnXml;
        }
        #endregion
 
        #region Put方式
        public string Put(string data, string uri)
        {
            return CommonHttpRequest(data, uri, "PUT");
        }
        #endregion
 
        #region POST方式实现
 
        public string Post(string data, string uri)
        {
            return CommonHttpRequest(data, uri, "POST");
        }
 
        public string CommonHttpRequest(string data, string uri, string type)
        {
            //Web访问对象,构造请求的url地址
            string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
 
            //构造http请求的对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //转成网络流
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
            //设置
            myRequest.Method = type;
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "application/json";
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;
            // 发送请求
            Stream newStream = myRequest.GetRequestStream();
            newStream.Write(buf, 0, buf.Length);
            newStream.Close();
            // 获得接口返回值
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string ReturnXml = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();
            return ReturnXml;
        }
        #endregion
 
        #region GET方式实现
        public string Get(string uri)
        {
            //Web访问对象64
            string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
 
            //构造一个Web请求的对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            // 获得接口返回值68
            //获取web请求的响应的内容
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
 
            //通过响应流构造一个StreamReader
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //string ReturnXml = HttpUtility.UrlDecode(reader.ReadToEnd());
            string ReturnXml = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();
            return ReturnXml;
        }
        #endregion
    }

(3)在Program.cs中的Main方法中,调用RestClient类为我们提供的方法对WebAPI服务器(这里是本机:http://localhost:8080/)发起访问:

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Program
    {
        static string restfulServiceUri = "http://localhost:8080/";
 
        static void Main(string[] args)
        {
            RestClient restClient = new RestClient(restfulServiceUri);
 
            #region 01.Get方式无参数请求
            Console.WriteLine("----------------------获取所有产品列表-----------------------");
            string getResult = restClient.Get("api/Product");
            Console.WriteLine(getResult);
            Console.WriteLine();
            #endregion
 
            #region 02.Get方式带参数请求
            Console.WriteLine("----------------------获取Id=1的产品信息-----------------------");
            string getByIdResult = restClient.Get("api/Product/1");
            Console.WriteLine(getByIdResult);
            Console.WriteLine();
            Console.WriteLine("----------------------获取Name=锤子手机的产品信息-----------------------");
            string getByNameResult = restClient.Get("api/Product/?productName=锤子手机");
            Console.WriteLine(getByNameResult);
            Console.WriteLine();
            Console.WriteLine("----------------------获取Category=移动电话的产品信息-----------------------");
            string getByTypeResult = restClient.Get("api/Product/?category=移动电话");
            Console.WriteLine(getByTypeResult);
            Console.WriteLine();
            #endregion
 
            #region 03.Post方式请求结果
            //Console.WriteLine("----------------------新增一个产品信息-----------------------");
            //string jsonParam = @"{Id:""250"",Name:""小米2S"",Category:""移动电话"",Price:""1800""}";
            //string postResult = restClient.Post(jsonParam, "api/Product");
            //Console.WriteLine(postResult);
            //getResult = restClient.Get("api/Product");
            //Console.WriteLine(getResult);
            //Console.WriteLine();
            #endregion
 
            #region 04.Delete方式请求结果
            //Console.WriteLine("----------------------删除一个产品信息-----------------------");
            //string deleteId = "6";
            //string deleteResult = restClient.Delete("api/Product/" + deleteId);
            //Console.WriteLine(deleteResult);
            //getResult = restClient.Get("api/Product");
            //Console.WriteLine(getResult);
            //Console.WriteLine();
            #endregion
 
            #region 05.Put方式请求结果
            Console.WriteLine("----------------------修改一个产品信息-----------------------");
            string jsonParam = @"{Id:""5"",Name:""PlayStation 3"",Category:""电视游戏机"",Price:""3200""}";
            string putResult = restClient.Put(jsonParam, "api/Product/5");
            Console.WriteLine(putResult);
            getResult = restClient.Get("api/Product");
            Console.WriteLine(getResult);
            Console.WriteLine();
            #endregion
 
            Console.ReadKey();
        }
    }

(4)调试运行,查看访问结果如下:可以看出,返回的均为JSON格式的数据,和我们在浏览器中访问指定URI的结果一致。

3.5 初探小结

ASP.NET Web API 是一种框架,用于轻松构建可以访问多种客户端(包括浏览器和移动设备)的 HTTP 服务。 ASP.NET Web API 是一种用于在 .NET Framework 上构建 RESTful 应用程序的理想平台。

第一个WebAPI项目的更多相关文章

  1. 在服务器中无法自宿主启动一个webapi项目,引出查看系统端口是否被占用

    在windows server下启动一个webapi的.net core项目报错 如下图: 让我以为服务器还需要别的配置.后来发现原来是线程被占用了. 在windows下查看某线程是否被占用的命令如下 ...

  2. [开源]快速构建一个WebApi项目

    项目代码:MasterChief.DotNet.ProjectTemplate.WebApi 示例代码:https://github.com/YanZhiwei/MasterChief.Project ...

  3. 20181124_webAPI基础01_创建一个基础的WebAPI项目

    1. webApi属于RESTful架构风格, 而RESTful风格, 是以资源为视角来描述服务的 2. 创建webAPI项目 3. 选择webAPI, 然后mvc会自动引用 4. 点击确定, 就创建 ...

  4. 基于.NET Core 框架搭建WebApi项目

    一 什么是.NET Core? 随着2014年 Xamarin和微软发起.NET基金会,微软在2014年11月份开放.NET框架源代码.在.NET开源基金会的统一规划下诞生了.NET Core .也就 ...

  5. VS2017 +NetCore2.2.0+WebApi项目整合SwaggerUI 以及遇到的坑

    1.新建一个WebApi项目,这里不说了. 2.打开项目nuget管理控制台,在 https://www.nuget.org/ 搜索swagger的包:Swashbuckle.AspNetCore , ...

  6. C# WebAPI项目,不支持HttpPut请求!!!

    有点标题党了,这个异常的现象是这样的: 我有一个正在跑的项目,要对接第三方厂家的设备.  对方给的接口文档,里面有一个接口是需要我这边实现的,要求必须是PUT请求方式. 所以我在项目基础上,新增一个W ...

  7. Angularjs,WebAPI 搭建一个简易权限管理系统 —— WebAPI项目主体结构(四)

    目录 前言 Angularjs名词与概念 Angularjs 基本功能演示 系统业务与实现 WebAPI项目主体结构 Angularjs 前端主体结构 5.0 WebAPI项目主体结构 5.1 总体结 ...

  8. Restful WebApi项目开发实践

    前言 踩过了一段时间的坑,现总结一下,与大家分享,愿与大家一起讨论. Restful WebApi特点 WebApi相较于Asp.Net MVC/WebForm开发的特点就是前后端完全分离,后端使用W ...

  9. Asp.net WebApi 项目示例(增删改查)

    1.WebApi是什么 ASP.NET Web API 是一种框架,用于轻松构建可以由多种客户端(包括浏览器和移动设备)访问的 HTTP 服务.ASP.NET Web API 是一种用于在 .NET ...

随机推荐

  1. console.log 加样式

    console.log("%c%s", "color: black; font-size: 18px;", "test")

  2. java登录密码效验

    密码校验需求: 1) 密码控制只能输入字母.数字.特殊符号(~!@#$%^&*()_+[]{}|\;:'",./<>?)2) 长度 6-16 位,必须包括字母.数字.特殊 ...

  3. 【转载】javadoc学习笔记和可能的注意细节

    转载自:http://www.cnblogs.com/xt0810/p/3630996.html [前面的话] 这次开发项目使用jenkins做持续集成,PMD检查代码,Junit做单元测试,还会自动 ...

  4. oracle之nomount、mount、open三种状态

    1.先来看下外国网站上的资料怎么说 Nomount – The database instance has been started (processes and memory structures ...

  5. 发布webService

    创建webservices项目 1>创建web项目>添加新建项>webService>确认 注:webservices项目相当于就是UI ******************* ...

  6. .NET架构师

    闲话不多扯,关于.NET架构师的培训  架构师的知识体系总结:7大重点,对7大重点作为细节的阐述将再后面陆续展开!架构师的体系纲领主要来着这7点.(必须严格记下) 1:现代软件开发过程及架构策略 1. ...

  7. Linux下nginx生成日志自动切割

    1.编辑切割日志的 shell 程序,目录自定 #vi /data/nginx/cut_nginx_log.sh 输入代码: #!/bin/bash # This script run at 00:0 ...

  8. 真实代理(RealProxy)在WCF中的运用

    在WCF中,当我们在调用服务端的方法时,一般有两点需要考虑:1.捕获服务端的异常信息,记录日志:2.及时关闭会话信道,当调用超时或调用失败时及时中断会话信道.我们一般会像下面这样处理(以Calcula ...

  9. 微信支付错误两个问题的解决:curl出错,错误码:60

    如下是运行微信支付测试代码时出错代码: Warning: curl_setopt() expects parameter 2 to be long, string given in D:\wwwroo ...

  10. jquery拖拽效果

    <!doctype html><html lang="en"><head> <meta charset="utf-8" ...