1.vs2015 新建一个mvc项目,勾选webapi
项目默认已经添加了webapi的路由:
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
这个默认的路由跟mvc默认路由有区别,它不带action,所以非常适合用来构建RESTFUL风格的服务
路由的申明要先于mvc,否则路由过来时,先从mvc的路由中匹配,导致匹配失败
2.新建一个Product类 和 相应的控制器 ProductsController
public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } }
public class ProductsController : ApiController { List<Product> products = new List<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 } }; public IEnumerable<Product> Get() { return products; } public IHttpActionResult Get(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { return NotFound(); } return Ok(product); } /// <summary> /// 添加 /// </summary> /// <param name="form">表单对象,它是唯一的</param> /// <returns></returns> public bool Post(Product entity) { products.Add(entity); return true; } public bool Put(Product entity) { var product = this.products.FirstOrDefault(p => p.Id == entity.Id); if (product != null) { product.Name = entity.Name; product.Category = entity.Category; product.Price = entity.Price; return true; } return false; } public bool Delete(string id) { return true; } }
3.前台调用
3.1 get: 其中data 对应的是查询参数,如果有则匹配Get(int id) 方法,它与在url中加参数 url: "api/products/1"效果是一样的,如果既在url里加参数又实用data,则url里的参数值会被data覆盖掉,也就是说Get(int id) 接收到的id会是data里指定的
function get() { $.ajax({ url: "api/products", type: "GET", data: { "ID": 1 }, success: function (data) { alert(JSON.stringify(data)); } }); }
3.2 post
var postdata = { Name: $("#Name").val(), Category: $("#Category").val(), Price: $("#Price").val() }; $.ajax({ type: ‘POST‘, url: ‘api/products‘, data: postdata, dataType: ‘json‘, success: function (data, textStatus) { alert("添加成功"); }, error: function (xmlHttpRequest, textStatus, errorThrown) { alert(‘errot:‘ + errorThrown); } });
3.3 put
var postData = { Id: $("#ID").val(), Name: $("#Name1").val(), Category: $("#Category1").val(), Price: $("#Price1").val(), }; $.ajax({ type: ‘PUT‘, url: ‘api/Products‘, data: postData, dataType: ‘json‘, success: function (data, textStatus) { alert("修改成功!"); $(‘#UpdateUserDialog‘).dialog(‘close‘); $("#test").datagrid("reload"); }, error: function (xmlHttpRequest, textStatus, errorThrown) { alert(‘errot:‘ + textStatus); } });
3.4 delete
$.ajax({ type: ‘DELETE‘, url: ‘api/products/‘ + ids, success: function (data, textStatus) { alert("删除成功!"); $("#test").datagrid("reload"); }, error: function (xmlHttpRequest, textStatus, errorThrown) { alert(‘errot:‘ + errorThrown); } });
4.问题
每中获取方式对应的方法只能有一个,如果声明两个[HttpPost]的方法,那么post调用时,就会报:500 的错
时间: 2024-10-10 05:25:38