首先新建 ApiController类 和一个Entity Framework数据实体
public class CustomersController : ApiController { //Select All public IEnumerable Get() { NorthwindEntities db = new NorthwindEntities(); var data = from item in db.Customers orderby item.CustomerID select item; return data.ToList(); } //Select By Id public Customer Get(string id) { NorthwindEntities db = new NorthwindEntities(); var data = from item in db.Customers where item.CustomerID == id select item; return data.SingleOrDefault(); } //Insert public void Post(Customer obj) { NorthwindEntities db = new NorthwindEntities(); db.Customers.AddObject(obj); db.SaveChanges(); } //Update public void Put(string id, Customer obj) { NorthwindEntities db = new NorthwindEntities(); var data = from item in db.Customers where item.CustomerID == id select item; Customer old = data.SingleOrDefault(); old.CompanyName = obj.CompanyName; old.ContactName = obj.ContactName; old.Country = obj.Country; db.SaveChanges(); } //Delete public void Delete(string id) { NorthwindEntities db = new NorthwindEntities(); var data = from item in db.Customers where item.CustomerID == id select item; Customer obj = data.SingleOrDefault(); db.Customers.DeleteObject(obj); db.SaveChanges(); } }
访问API的方式为:localhost/api/customers,在实际中将要根据情况替换合适的端口,默认所有的WEB API都是通过/api根目录的方式访问的,该路由是在Global.asax下进行定义,如下:
public static void RegisterRoutes(RouteCollection routes)
{
...
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
...
}
protected void Application_Start() { HttpConfiguration config = GlobalConfiguration.Configuration; JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new IsoDateTimeConverter()); JsonNetFormatter formatter = new WebAPIDemo.Http.Formatters.JsonNetFormatter(settings); config.Formatters.Insert(0, formatter); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); BundleTable.Bundles.RegisterTemplateBundles(); }
jQuery去调用WEB API
html:
<table id="customerTable" border="0" cellpadding="3"> <tr> <th>Customer ID</th> <th>Company Name</th> <th>Contact Name</th> <th>Country</th> <th>Actions</th> </tr> <tr> <td><input type="text" id="txtCustomerId" size="5"/></td> <td><input type="text" id="txtCompanyName" /></td> <td><input type="text" id="txtContactName" /></td> <td><input type="text" id="txtCountry" /></td> <td><input type="button" name="btnInsert" value="Insert" /></td> </tr> </table>
<script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
然后在jQuery中,通过$.getJSON的方法,调用WEB API,代码如下:
$(document).ready(function () {
$.getJSON("api/customers", LoadCustomers);
});
熟悉jQuery的朋友肯定明白,$.getJson方法中第一个参数是调用服务的地址,第二个参数是回调方法,这个回调方法LoadCustomers中,将展示服务端web api返回的数据,代码如下
function LoadCustomers(data) {
$("#customerTable").find("tr:gt(1)").remove();
$.each(data, function (key, val) {
var tableRow = '<tr>' +
'<td>' + val.CustomerID + '</td>' +
'<td><input type="text" value="' + val.CompanyName + '"/></td>' +
'<td><input type="text" value="' + val.ContactName + '"/></td>' +
'<td><input type="text" value="' + val.Country + '"/></td>' +
'<td><input type="button" name="btnUpdate" value="Update" />
<input type="button" name="btnDelete" value="Delete" /></td>' +
'</tr>';
$('#customerTable').append(tableRow);
});
$("input[name='btnInsert']").click(OnInsert);
$("input[name='btnUpdate']").click(OnUpdate);
$("input[name='btnDelete']").click(OnDelete);
}
在上面的代码中,首先移除所有表格中的行(除了表头外),然后通过jQuery中的each方法,遍历web api返回给前端的数据,最后展现所有的数据行。然后在Insert,update,delete三个按钮中都绑定了相关的方法函数,下面先看 update的代码:
function OnUpdate(evt) { var cell; var customerId = $(this).parent().parent().children().get(0).innerHTML; cell = $(this).parent().parent().children().get(1); var companyName = $(cell).find('input').val(); cell = $(this).parent().parent().children().get(2); var contactName = $(cell).find('input').val(); cell = $(this).parent().parent().children().get(3); var country = $(cell).find('input').val(); var data = '{"id":"' + customerId + '", "obj":{"CustomerID":"' + customerId + '","CompanyName":"' + companyName + '","ContactName":"' + contactName + '","Country":"' + country + '"}}'; $.ajax({ type: 'PUT', url: '/api/customers/', data: data, contentType: "application/json; charset=utf-8", dataType: 'json', success: function (results) { $.getJSON("api/customers", LoadCustomers); alert('Customer Updated !'); } }) }
在上面的代码中,首先从每行的各个文本框中获得要更新的值,然后组织成JSON数据,
其数据格式为包含两项,其中一项包含customer的ID,另外一个是新的customer实体对象,因为WEB API的PUT方法需要的是两个参数。
然后通过jQuery的$.ajax方法进行调用web api,注意这里的type指定为put方法,并且注意编码为UTF-8,然后在回调方法success中,再此使用$.getJSON方法,获得更新后的最新用户列表。
而Insert,Delete的方法代码如下:
function OnInsert(evt) { var customerId = $("#txtCustomerId").val(); var companyName = $("#txtCompanyName").val(); var contactName = $("#txtContactName").val(); var country = $("#txtCountry").val(); var data = '{"obj":{"CustomerID":"' + customerId + '","CompanyName":"' + companyName + '","ContactName":"' + contactName + '","Country":"' + country + '"}}'; $.ajax({ type: 'POST', url: '/api/customers/', data: data, contentType: "application/json; charset=utf-8", dataType: 'json', success: function (results) { $("#txtCustomerId").val(''); $("#txtCompanyName").val(''); $("#txtContactName").val(''); $("#txtCountry").val(''); $.getJSON("api/customers", LoadCustomers); alert('Customer Added !'); } }) } function OnDelete(evt) { var customerId = $(this).parent().parent().children().get(0).innerHTML; var data = '{"id":"' + customerId + '"}'; var row = $(this).parent().parent(); $.ajax({ type: 'DELETE', url: '/api/customers/', data: data, contentType: "application/json; charset=utf-8", dataType: 'json', success: function (results) { $.getJSON("api/customers", LoadCustomers); alert('Customer Deleted!'); } }) }
尽管ASP.NET WEB API是ASP.NET MVC的其中一部分,但并没规定只能在ASP.NET MVC架构中使用,可以在WebForm中进行调用,方法如下:
我们继续在解决方案中新建一个Web Application,然后在应用中增加一个普通的asp.net Web Form页面,然后将之前的API文件夹复制到这个新的web项目的根目录中。
然后和之前的步骤一样,通过Entitiy Framework建立customer实体类,然后打开Global.ascx,写入代码如下:
protected void Application_Start(object sender, EventArgs e) { HttpConfiguration config = GlobalConfiguration.Configuration; JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new IsoDateTimeConverter()); JsonNetFormatter formatter = new WebAPIWebFormDemo.Http.Formatters.JsonNetFormatter(settings); config.Formatters.Insert(0, formatter); RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = System.Web.Http.RouteParameter.Optional } ); }
这里做了两个事情,首先在WEB API框架中注册了自定义的JSON解析器,然后是注册了web api 控制器的路由。 然后将前文说到的使用jQuery 调用web api的所有代码都复制到index.aspx(或default.aspx)中去。