Web API相对WCF优势,以及构建WebApi

 在企业级开发过程中,为了让系统具有更高的扩展性以及便于维护,通常都会使用web api和wcf技术来把系统切割成一个个功能点,发布出去,供前端调取。那么问题来了,有些人不仅要问,既然有了wcf,为什么还要搞一套webapi呢?会不会有点画蛇添足呢?

      使用过wcf技术的人大都知道它的一些基础特性吧。在这里不做多说了,现在就说我为什么要选择webapi的原因:wcf是基于soap协议,数据格式是xml,而webapi是基于RESTful标准的,数据格式多样化,例如xml,json,ATOM。wcf配置繁琐,而webapi它是简单,代码可读性强的,上手快的,如果要拿它和web服务相比,我会说,它的接口更标准,更清晰,没有混乱的方法名称,有的只有几种标准的请求,如get,post,put,delete等,它们分别对应的几个操作。更重要的是它仅仅是一个URL链接,可以在不同的平台运转,同时支持MVC的特征,像路由、控制器、action、filter、模型绑定、控制反转(IOC)或依赖注入(DI),单元测试。这些可以使程序更简单、更健壮。

     如何来创建一个webapi接口呢?

     web api是在vs2012上的mvc4项目绑定发行,所以首先打开vs2012,创建一个webapi项目

     ApiController部分的代码:

    Get操作:

    

下面我们看看返回结果:

Post操作:

webapi代码:

/// <summary>
/// post操作
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
[HttpPost]
public HttpResponseMessage AddUser([FromBody] Users entity)
{
_userList.Add(entity);
return new HttpResponseMessage { Content = new StringContent(JsonTool.EntityToJson<List<Users>>(_userList), Encoding.UTF8, "application/json") };
}

调用post操作

js代码:

function testpost() {
$.ajax({
url: 'http://localhost:2779/api/Test/AddUser/',
type: 'post',
dataType: 'json',
data: { "UserID": "4", 'UserName': "test", 'UserEmail': "123456@qq.com" },
success: function (data) {
alert(data);
}
});

}

返回结果:

put更新操作:

webapi代码:

[HttpPut]
public HttpResponseMessage PutUser(int id, [FromBody] Users entity)
{
var user = _userList.FirstOrDefault(i => i.UserID == id);
if (user != null)
{
user.UserName = entity.UserName;
user.UserEmail = entity.UserEmail;
}
return new HttpResponseMessage { Content = new StringContent(JsonTool.EntityToJson<List<Users>>(_userList), Encoding.UTF8, "application/json") };
}

js代码:

function putpost() {
$.ajax({
url: 'http://localhost:2779/api/Test/PutUser/?id=1',
type: 'put',
dataType: 'json',
data: { "UserID": "1", 'UserName': "test1", 'UserEmail': "test123456@qq.com" },
success: function (data) {
alert(data);
}
});

}

提交put更新操作结果:

delete操作:

webapi代码:

/// <summary>
/// 删除
/// </summary>
/// <param name="id">主键</param>
/// <returns></returns>
[HttpDelete]
public HttpResponseMessage Delete(int id)
{
_userList.Remove(_userList.FirstOrDefault(i => i.UserID == id));
return new HttpResponseMessage { Content = new StringContent(JsonTool.EntityToJson<List<Users>>(_userList), Encoding.UTF8, "application/json") }; 
}

js代码:

function deletes() {
$.ajax({
url: 'http://localhost:2779/api/Test/Delete/?id=1',
type: 'DELETE',
dataType: 'json',
success: function (data) {
alert(data);
}
});

}

至此我们就完成了webapi 四种基本操作方式的代码构建,各位是不是觉得很简单呢?

感谢您的阅读!

原文地址:https://www.cnblogs.com/dzycwy/p/5309198.html