您现在的位置是:网站首页> 编程资料编程资料
ASP.NET中Web API的简单实例_实用技巧_
2023-05-24
302人已围观
简介 ASP.NET中Web API的简单实例_实用技巧_
一、Web API的路由
1、在Visual Studio中新建MVC4项目,在App_Start目录下有一个WebApiConfig.cs文件,这个文件中就是相应的Web API的路由配置了。
2、Web API 框架默认是基于 Restful 架构模式的,与ASP.NET MVC 有区别的是,它会根据 Http 请求的 HttpMethod(Get、Post、Put、Delete)来在Controller 中查找 Action,规则是:Action 名中是否以Get、Post 开头?Action 上标记 HttpGet、HttpPost 等标记?
3、当然可以修改默认的配置,让客户端在调用时显式指定 action 名称,例如
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); 这样,由于显式指定了 Action 名称,Web API 会使用该名称来查找对应的 Action 方法,而不再按照 HttpMethod 约定来查找对应的 Action。
二、ASP.NET中Web API的简单实例
1、Get请求数据
(1)、定义一个UserModel 类
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提交数据
(1)、UserController 里面添加一个Action
public bool add(UserModel user) { return user != null; } (2)、页面上添加一个button
(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路由介绍,希望对大家的学习有所帮助。
相关内容
- 创建一个完整的ASP.NET Web API项目_实用技巧_
- ASP.NET MVC中图表控件的使用方法_实用技巧_
- SqlCommandBuilder类批量更新excel或者CSV数据的方法_实用技巧_
- asp.net操作Word实现批量替换_实用技巧_
- 三种asp.net页面跳转的方法_实用技巧_
- SqlCommandBuilder如何实现批量更新_实用技巧_
- ASP.NET MVC 3仿Server.Transfer效果的实现方法_实用技巧_
- asp.net实现识别客户端浏览器或操作系统_实用技巧_
- Asp.Net MVC3.0如何项目部署到Win7 64位系统_实用技巧_
- asp.net操作过程中常见错误的解决方法_实用技巧_
