1.创建空的WebApi 项目
创建成功后的引用
项目中的全局文件
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Routing; namespace WebApiThree { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); } } }
项目中的api配置和路由
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace WebApiThree { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服务 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }----------------------------------------------------------------HelloWord实例————————————————————————————————————
1.WebApi控制器
/// <summary> /// 访问控制器 /// </summary> public class ProductsController : ApiController { Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } }; /// <summary> /// 获取列表 /// </summary> /// <returns></returns> public IEnumerable<Product> GetAllProducts() { return products; } /// <summary> /// 获取对象 /// </summary> /// <param name="id">兑现ID</param> /// <returns></returns> public IHttpActionResult GetProduct(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { return NotFound(); } return Ok(product); } }
2.使用JavaScript访问接口
<div> <h2>All Products</h2> </div> <ul id="products" /> <div> <h2>Search by ID</h2> <input type="text" id="prodId" size="5" /> <input type="button" value="Search" onclick="find();" /> <p id="product" /> </div> <script src="../Scripts/jquery-1.11.1.min.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 + ': $' + item.Price; } 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>