ASP.NET中Web API的简单实例

 更新时间:2021年9月22日 10:09  点击:1756

一、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

<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路由介绍,希望对大家的学习有所帮助。

[!--infotagslink--]

相关文章