webapi简介
在asp.net中,创建一个HTTP服务,有很多方案,以前用ashx,一般处理程序(HttpHandler),现在可以用webapi
微软的web api是在vs2012上的mvc4项目绑定发行的,它提出的web api是完全基于RESTful标准的,完全不同于之前的(同是SOAP协议的)wcf和webService,它是简单,代码可读性强的,上手快的,如果要拿它和web服务相比,我会说,它的接口更标准,更清晰,没有混乱的方法名称,有的只有几种标准的请求,如get,post,put,delete等,它们分别对应的几个操作,下面讲一下:
GET:获取
POST:添加
PUT:修改
DELETE:删除
注意上面公开的API接口都是在XMLHttpRequest情况下调用的,当然你可以使用jquery的ajax组件来完成这个请求调用,它的代码更加面向对象,下面会举例说明。
WebAPI是根据请求头信息(Accept Header)来查找已经格式化注册的响应头信息(Content-Type)来确定它应该返回的输出类型json/xml,浏览器访问基本都是xml,如果只需要json的话可以通过Global.asax设置
protected void Application_Start(object sender, EventArgs e)
{//默认JSON
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
webapi示例(CRUD)
环境:vs2015、iis7、webapi2.0、.net4.5.2
功能:webapi+ajax实现增删改查
模型
namespace cms.Model
{public partial class student
{
public int ID { get; set; }
public string name { get; set; }
public int sex { get; set; }
public int age { get; set; }
public System.DateTime timesAdd { get; set; }
}
}
修改webapi路由
webapi默认路由api/{controller}/{id},如果不喜欢可以修改为api/{controller}/{action}/{id},下边是修改后的代码
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Controller代码
using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Http;
using cms.BLL;
using cms.Model;
namespace cms.Web.API
{
public class StudentController : ApiController
{
public studentBLL bll = new studentBLL();
// GET: /api/student/GetList
public IEnumerable<student> GetList()
{
var list = bll.FindList();
return list;
} // GET: api/Student/Get/5
public student Get(int id)
{
var model = bll.Find(id);
if (model == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return model;
}
//添加方法1:如果要添加的字段和模型刚好匹配就用这个
// POST: api/Student/Post
public student Post([FromBody]student entity)
{
entity.timesAdd = DateTime.Now;
return bll.Add(entity); //dynamic data = new { name = _name, age = _age };
//return Json<dynamic>(data);
}
//添加方法2:如果要添加的字段和模型不匹配就用这个
// POST: api/Student/PostAdd
//注意:webapi post接受数据dynamic,ajax调用时也得把json格式化为字符串才行
public student PostAdd(dynamic obj)
{
student model = new student();
model.name = obj.name;
model.sex = obj.sex;
model.age = obj.age;
model.timesAdd = DateTime.Now;
return bll.Add(model);
} // PUT: api/Student/Put/5
public void Put(int id, [FromBody]student entity)
{
student model = bll.Find(id);
model.name = entity.name;
model.sex = entity.sex;
model.age = entity.age;
if (!bll.Update(model))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
} // DELETE: api/Student/Delete/5
public void Delete(int id)
{
if (!bll.Delete(id))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
}
}
html代码
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>webapi教程</title>
<script type="text/javascript" src="Scripts/jquery-1.8.2.js"></script>
<style type="text/css">
h2 {
border-bottom: solid 1px #ccc;
padding-bottom: 10px;
} #box_list span {
margin-right: 30px;
width: 100px;
display: inline-block;
} .time {
width: 200px !important;
}
</style>
</head>
<body>
<h2>webapi create</h2>
<div>
<p><input type="hidden" id="iid" /></p>
<p>姓名:<input type="text" id="name" /></p>
<p>性别:<input type="text" id="sex" /></p>
<p>年龄:<input type="text" id="age" /></p>
<p><input type="button" id="btnAdd" value="添加" />
<input type="button" id="btnAdd2" value="添加2" />
<input type="button" id="btnEdit" value="修改" /></p>
</div> <h2>webapi list</h2>
<div id="box_list"></div>
<div>
<input type="button" id="btnDel" value="删除" />
<input type="button" id="btnView" value="查看" />
</div>
<div id="box_view"></div>
<script type="text/javascript">
$(function () {
GetList();
$("#btnAdd").click(function () {
var _data = { name: $("#name").val(), sex: $("#sex").val(), age: $("#age").val() };
$.ajax({
type: "post",
url: "/api/Student/Post",
data: _data,
dataType: "json",
success: function (data) {
alert("添加成功");
GetList();
},
error: function () {
alert("添加失败");
}
});
})
$("#btnAdd2").click(function () {
var _data = JSON.stringify({ name: $("#name").val(), sex: $("#sex").val(), age: $("#age").val() });
$.ajax({
type: "post",
url: "/api/Student/PostAdd",
data: _data,
dataType: "json",
contentType: 'application/json',
success: function (data) {
alert("添加成功");
GetList();
},
error: function () {
alert("添加失败");
}
});
})
$("#btnDel").click(function () {
var _iid = $('input:radio[name=iid]:checked').val();;
$.ajax({
type: "Delete",
url: "/api/Student/Delete/" + _iid,
success: function (data) {
alert("删除成功");
$('input:radio[name=iid]:checked').parents("p").remove();
},
error: function () {
alert("删除失败");
}
});
})
$("#btnView").click(function () {
var _iid = $('input:radio[name=iid]:checked').val();;
$.ajax({
type: "get",
url: "/api/Student/get/" + _iid,
dataType: "json",
success: function (data) {
name: $("#iid").val(data.ID);
name: $("#name").val(data.name);
sex: $("#sex").val(data.sex);
age: $("#age").val(data.age)
},
error: function () {
alert("获取失败");
}
});
})
$("#btnEdit").click(function () {
var _data = { name: $("#name").val(), sex: $("#sex").val(), age: $("#age").val() };
$.ajax({
type: "put",
url: "/api/Student/Put/" + $("#iid").val(),
data: _data,
success: function (data) {
alert("修改成功");
GetList();
},
error: function () {
alert("修改失败");
}
});
})
})
function GetList()
{
$("#box_list").html("");
$.ajax({
type: "GET",
url: "/api/student/GetList",
dataType: "json",
success: function (data) {
$.each(data, function (i, item) {
$("#box_list").append("<p><span><input type='radio' name='iid' value='" + item.ID + "' />" + item.ID + "</span><span>" + item.name + "</span><span>" + item.sex + "</span><span>" + item.age + "</span><span class='time'>" + item.timesAdd + "</span></p>")
});
}
});
}
</script>
</body>
</html>
效果图
常见问题:
如果在做修改和删除操作时报错误(webapi delete Method Not Allowed),说明是iis把put和delete请求禁止了,需要在web.config中设置一下就ok了
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
</handlers>
</system.webServer>