1 新建空的ASP.NET应用程序
2.在引用里面选择管理nuget程序包,搜索webapi,下载包
3 在工程下面建Controller和Models文件夹
4 在Models文件夹下面新建类 Storage
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ManualWebApi.Models
{
public static class Storage
{
public static IEnumerable<Student> Students { get; set; }
public static IEnumerable<Teacher> Teachers { get; set; }
static Storage()
{
Students = new List<Student>()
{
new Student(){ Age=11, Gender=false, Id=1, Name="zs1" },
new Student(){ Age=12, Gender=false, Id=2, Name="zs2" },
new Student(){ Age=13, Gender=false, Id=3, Name="zs3" },
new Student(){ Age=14, Gender=false, Id=4, Name="zs4" },
new Student(){ Age=15, Gender=false, Id=5, Name="zs5" },
};
Teachers = new List<Teacher>();
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public bool Gender { get; set; }
}
public class Student:Person
{
}
public class Teacher:Person
{
}
}
5 在Controller文件夹下面建StudentsController类,让其继承于ApiControllerr
using ManualWebApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace ManualWebApi.Controller
{
public class StudentsController:ApiController
{
public IEnumerable<Student> Get()
{
return Storage.Students;
}
public Student Get(string name)
{
return Storage.Students.FirstOrDefault(s => s.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));
}
public void Post(Student entity)
{
entity.Id = Storage.Students.Max(s => s.Id) + 1;
var list = Storage.Students as IList<Student>;
list.Add(entity);
}
public void Put([FromUri]string name,[FromBody] Student entity)
{
Delete(name);
Post(entity);
}
public void Delete([FromUri]string name)
{
var stu = Get(name);
var list = Storage.Students as IList<Student>;
list.Remove(stu);
}
}
}
6 新建全局文件Global.asax,增加路由
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using System.Web.SessionState;
namespace ManualWebApi
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configuration.Routes.MapHttpRoute("default-api","api/{controller}/{name}",new { name = RouteParameter.Optional });
}
}
}
7 运行,在地址栏输入http://localhost:56982/api/students,打开postman输入网址则得到json数据
8 输入http://localhost:56982/api/students/zs1 测试Get方法
9.选择post,在Body里面输入数据,测试Post方法
10 选择Delete, 输入http://localhost:56982/api/students/zs1 ,发送命令后再执行Get来测试Delete方法
11 选择PUT,输入http://localhost:56982/api/students/zs2,Body里面输入新的数据,发送命令后,再执行Get,测试Put方法
json数据
[
{
"Id": 1,
"Name": "zs1",
"Age": 11,
"Gender": false
},
{
"Id": 2,
"Name": "zs2",
"Age": 12,
"Gender": false
},
{
"Id": 3,
"Name": "zs3",
"Age": 13,
"Gender": false
},
{
"Id": 4,
"Name": "zs4",
"Age": 14,
"Gender": false
},
{
"Id": 5,
"Name": "zs5",
"Age": 15,
"Gender": false
}
]