是什么
Web Api,网络应用程序接口。它包含了广泛的功能,网络应用通过API接口,可以实现存储服务、消息服务、计算服务的能力,利用这些能力可以进行开发出强大功能的web应用。简单来说,就是一个接口,比如说,我们要做前后端分离的项目,前端和后端通过url连接,但是我们如何知道后端的数据是否通了,返回的数据是否正确,于是我们通过这个接口知道。
相似的技术
postman和swagger。
使用步骤
1.创建web api项目(本例使用vs2015)
文件--新建--项目--ASP.NET Web应用程序
2.选择模板中的Web API模板
[RoutePrefix("api/ghost")]
创建web api项目完成。
3.代码编写
B、D层以前怎么写现在就怎么写,controller需要添加一些特殊的代码。
步骤一:删除using System.Web.Mvc; 添加using System.Web.Http;
步骤二:给类起个名,路由中要找到这个类,所以我要先给这个类起个名字:
[RoutePrefix("api/ghost")]
步骤三:controller继承ApiController
步骤四:给方法起个名字,原理同给类起个名字一样,路由找到类后去找方法:
[HttpGet] [Route("goodsDetail")]完整的代码参考:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using Model; using ViewModel; using Services; namespace WebApi.Controllers { [RoutePrefix("api/ghost")] public class ghostController : ApiController { List<ghostVM> goods = new List<ghostVM>(); ghostService goodService = new ghostService(); [HttpGet] [Route("goodsDetail")] public List<ghostVM> goodsDetail() { string id = "1"; goods = goodService.goodsDetail(id); if (goods == null) { return null; } else { return goods; } } } }4.测试,这时要安装WebApiTestClient。
任务栏工具--NuGet包管理器--管理解决方案的NuGet程序包--浏览搜索WebApiTestClient--安装WebApi
5.在WebApi下的Areas/HelpPage/Views/Help/Api.cshtml的最后添加以下代码:
@Html.DisplayForModel("TestClientDialogs") @section Scripts{ <link href='~/Areas/HelpPage/HelpPage.css' rel='stylesheet' /> @Html.DisplayForModel("TestClientReferences") }6.运行项目,在网页上点击API,点击对应的类名/方法名,点击Test API,就可以看到是否连接数据库正确了。