标签:des style blog http io color ar os 使用
1.Web项目
1.1概述
上一例子,我们”折腾“操作的是字符串,显然它不常用。这次我们玩一下实体类,毕竟面向对象开发是需要实体类来存储和传输数据的。
1.2创建项目
和上一例子创建项目一样:

1.3添加实体类
在Models文件夹下,添加Product.cs类,其代码:
namespace WebApi04.Models
{
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public string Genre { get; set; }
}
}
1.4添加控制器
在Controllers文件夹下,(删除ValuesController.cs)添加ProductsController.cs,其代码:
using System.Collections.Generic;
using System.Web.Http;
using WebApi04.Models;
using System.Linq;
namespace WebApi04.Controllers
{
public class ProductsController : ApiController
{
//模拟数据
static List<Product> products = InitList();
private static List<Product> InitList()
{
var list = new List<Product>
{
new Product{ID=1,Name="联想500", Genre="电脑"},
new Product{ID=2,Name="苹果5s", Genre="手机"},
new Product{ID=3,Name="HP500", Genre="电脑"},
new Product{ID=4,Name="三星Note4", Genre="手机"},
new Product{ID=5,Name="IBM X86", Genre="电脑"},
new Product{ID=6,Name="屌丝", Genre="逼格"}
};
return list;
}
// GET: api/Products
/// <summary>
/// 查询所有
/// </summary>
/// <returns>产品集合</returns>
public IEnumerable<Product> GetProducts()
{
return products;
}
/// <summary>
/// 根据id查询
/// </summary>
/// <param name="id">产品id</param>
/// <returns>单个产品</returns>
public Product Get(int id)
{
var product = (from p in products where p.ID == id select p).FirstOrDefault();
return product;
}
}
}
1.5查询所有
运行网站后,打开fiddler工具:

查看结果:

1.6查询单个

1.7查询单个不存在
查询id=100,这个模拟数据中没有。

它返回的结果是null或提示非法的,可它的状态码Result,还是200(如果前面操作字符集合例子,程序会提示索引范围出错,状态码也不是200),显然不合理了。
最好不存在的,状态码为404。
修改ProductsController.cs中Get(int id),其代码:
//如果查询单个实体不存在,返回404状态码
/// <summary>
/// 根据id查询
/// </summary>
/// <param name="id">产品id</param>
/// <returns>响应消息</returns>
public HttpResponseMessage Get(int id)
{
var product = (from p in products where p.ID == id select p).FirstOrDefault();
if (product != null)
{
return Request.CreateResponse<Product>(HttpStatusCode.OK, product);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "不存在");
}
}
需要添加下列命名空间:using System.Net.Http;using System.Net;
再一次测试查询:

修改ProductsController.cs中Get(int id),还可以使用以下方式(结果就不截图了):
// 如果查询单个实体不存在,返回404状态码
[ResponseType(typeof(Product))]
public IHttpActionResult Get(int id)
{
var product = (from p in products where p.ID == id select p).FirstOrDefault();
if (product == null)
{
return NotFound();
}
return Ok(product);
}
需要引入using System.Web.Http.Description;
1.8添加一个
在ProductsController.cs中,添加以下代码:
// POST api/values
/// <summary>
/// 添加产品
/// </summary>
/// <param name="product">产品实体</param>
/// <returns>响应消息</returns>
public HttpResponseMessage Post([FromBody]Product product)
{
products.Add(product);
var msg = Request.CreateResponse(HttpStatusCode.Created);
msg.Headers.Location = new System.Uri(Request.RequestUri + (products.Count).ToString());
return msg;
}
运行测试:

其结果:

1.9修改视图
前面我们是使用fiddler工具来查看的,可数据如何在网页上显示?
Home\Index.cshtml代码修改:
<ul id="prod"></ul>
@section scripts
{
<script>
$.ajax({
url: ‘/api/products‘,
success: function (data) {
var producList = $(‘#prod‘);
for (var i = 0; i < data.length; i++) {
var product = data[i];
producList.append(‘<li>‘ + product.Name + ‘</li>‘);
}
}
})
</script>
}
浏览首页:

1.10添加默认页
上面使用了Razorle ,我们也可以直接使用静态html页,在根目录下添加Defaut.html,其代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>产品</title>
</head>
<body>
<div>
<h2>所有产品</h2>
<ul id="products" />
</div>
<div>
<h2>根据id查询</h2>
<input type="text" id="prodId" />
<input type="button" value="Search" onclick="find();" />
<p id="product" />
</div>
<script src="Scripts/jquery-1.10.2.js"></script>
<script>
var uri = ‘api/products‘;
$(document).ready(function () {
$.getJSON(uri)
.done(function (data) {
$.each(data, function (key, item) {
$(‘<li>‘, { text: formatItem(item) }).appendTo($(‘#products‘));
});
});
});
function formatItem(item) {
return item.Name
}
//查询
function find() {
var id = $(‘#prodId‘).val();
$.getJSON(uri + ‘/‘ + id)
.done(function (data) {
$(‘#product‘).text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$(‘#product‘).text(‘Error: ‘ + err);
});
}
</script>
</body>
</html>
浏览此页:

(注:用jquey 请求和绑定数据,代码量比较高了。后面教程会使用Knockout.js来举例)
2.小结
本例你又能学到什么?希望你有兴趣继续看下去。当然,没有写删除和修改方法了,你可以体会仿前面的例子写就是了。
WebApi学习笔记04:使用webapi模板--实体类--状态码--视图
标签:des style blog http io color ar os 使用
原文地址:http://www.cnblogs.com/elder/p/4074239.html