從這一層開始我們開始不再創建.Framework類庫項目,而是WebAPI項目。
右鍵解決方案名,添加WebAPI項目:
生成好後,將Model層中App.config的連接字符串加到Web.config中,將Model層中App.config的連接字符串加到Web.config中,
將Model層中App.config的連接字符串加到Web.config中,重說三!
然後,用Nuget添加EF依賴,右擊項目名->添加->引用,把那三層引用進來。
右擊Controllers目錄,添加一個控制器(取名PersonController):
生成好後可以先跑起來看看效果,將WebAPI設置爲啓動項目,Ctrl+F5,輸入uri:
然後重點編輯string get(int id)這個方法,調用Services層對象的方法:
using MyWebAPI.Bussiness.Services;
using MyWebAPIDemo.DAL.Model;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Web.Http;
namespace MyWebAPI.WebAPI.Controllers
{
public class PersonController : ApiController
{
private PersonService service = new PersonService();
// GET: api/Person
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Person/5
public string Get(int id)
{
List<Person> list = service.getAllPerson();
return JsonConvert.SerializeObject(list);
}
// POST: api/Person
public void Post([FromBody]string value)
{
}
// PUT: api/Person/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/Person/5
public void Delete(int id)
{
}
}
}
運行效果:
自此,整個項目完成,一個很小的三層WebAPI就搞定了。