ASP.NET中Web API的简单实例 |
本文标签:ASP.NET,Web,API 一、Web API的路由 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); 这样,由于显式指定了 Action 名称,Web API 会使用该名称来查找对应的 Action 方法,而不再按照 HttpMethod 约定来查找对应的 Action 。 public class UserModel { public string UserID { get; set; } public string UserName { get; set; } } (2)、添加一个Web API Controller :UserController public class UserController : ApiController { public UserModel getAdmin() { return new UserModel() { UserID = "000", UserName = "Admin" }; } } (3)、在浏览器访问:api/user/getadmin (默认返回的是XML数据模型) (4)、AJAX请求这个api,指定数据格式为json $.ajax({ type: GET, url: api/user/getadmin, dataType: json, success: function (data, textStatus) { alert(data.UserID + " | " + data.UserName); }, error: function (xmlHttpRequest, textStatus, errorThrown) { } }); 2、POST提交数据 public bool add(UserModel user) { return user != null; } (2)、页面上添加一个button <input type="button" name="btnOK" id="btnOK" value="发送POST请求" /> (3)、JS post提交数据 $(#btnOK).bind(click, function () { //创建ajax请求,将数据发送到后台处理 var postData = { UserID: 001, UserName: QeeFee }; $.ajax({ type: POST, url: api/user/add, data: postData, dataType: json, success: function (data, textStatus) { alert(data); }, error: function (xmlHttpRequest, textStatus, errorThrown) { } }); }); 以上就是ASP.NET中Web API的简单实例,还包括Web API路由介绍,希望对大家的学习有所帮助 。 |