Web API系列之三 基本功能实现
Web API系列之二讲解了如何搭建一个WebApi的基架,本文主要在其基础之上实现基本的功能.下面开始逐步操作:
一、配置WebApi的路由-用于配置外部如何访问内部资源的url的规则
1、添加Global.asax文件
右键项目-选择添加新项
添加成功,修改Global.asax.cs文件,代码如下:
using System; using System.Web.Http; namespace WebApiApp { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { //配置WebApi的路由 GlobalConfiguration.Configuration.Routes.MapHttpRoute( name:"default_api", routeTemplate: "{controller}/{item}", defaults: new { item=RouteParameter.Optional} ); } } }
ok,路由配置完成
二、模拟数据仓储,用于提供测试的数据,代码如下:
using System.Collections.Generic; namespace WebApiApp.Models { public static class Storages { public static IEnumerable<Student> Students { get; set; } static Storages() { Students = new List<Student> { new Student{Id=1,Name="张1" }, new Student{Id=2,Name="张2" }, new Student{Id=3,Name="张3" } }; } } public class Student { public int Id { get; set; } public string Name { get; set; } } }
三、编写Api控制器,通过该控制器向外部暴露数据
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using WebApiApp.Models; namespace WebApiApp.Controllers { /// <summary> /// 当前控制器下的所有方法相当于是一个关于学生资源的集合,里面封装着对学生的所有操作. /// </summary> public class StudentController:ApiController { /// <summary> /// Get /students/ -return student list /// </summary> /// <returns></returns> public IEnumerable<Student> Get() { return Storages.Students; } /// <summary> /// Get /students/zhangsan -return entity /// </summary> /// <returns></returns> public Student Get(string name) { return Storages.Students.FirstOrDefault(w => w.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)); } } }
至此基本功能全部实现,现在可以开始运行项目,测试功能.
四、测试
向浏览器中输入 项目地址/Student
项目地址/Student?name=张1
ok,说明项目部署成功.
注:服务器端返回xml的原因是:浏览器向服务端请求的就是xml数据,如下图示:
Chrome浏览器接收服务器端返回的数据类型默认的优先级是:html>xhtml+xml>xml>webp>所有(前面的类型都没有的话就所有了咯)