在ASP.NET CORE MVC中,Web API是其中一個功能子集,可以直接使用MVC的特性及路由等功能。
在成功構建 ASP.NET CORE MVC項目之後,選中解決方案,先填加一個API的文件夾,填加後,選中API文件夾,
選擇新建項,選擇填加Web API控制器,要注意控制器在命名時,是以Controller結尾的,這個不能改,前面的隨意,比如,此處以NoteController.cs爲例
填加後,打開NoteController.cs,系統已經幫我們構建好了一些基礎的功能,我們需要在其基礎上進行一些個性化修改使其成爲我們自己的代碼。
private INoteRespository _noteRespository; //引入note的(業務邏輯層,姑且稱爲業務邏輯層吧)
private INoteTypeRepository _noteTypeRepository; //引入notetype的(業務邏輯層,姑且稱爲業務邏輯層吧)
public NoteController(INoteRespository noteRespository, INoteTypeRepository noteTypeRepository) //構造行數初始化
{
this._noteRespository = noteRespository;
this._noteTypeRepository = noteTypeRepository;
}
// GET: api/note
[HttpGet]
public IActionResult Get(int pageindex=1) //分頁獲取
{
var pagesize = 10;
var notes = _noteRespository.PageList(pageindex, pagesize);
ViewBag.PageCount = notes.Item2;
ViewBag.PageIndex = pageindex;
var result = notes.Item1.Select(r => new NoteViewModel
{
Id = r.Id,
Tile = string.IsNullOrEmpty(r.Password)?r.Tile:"內容加密",
Content = string.IsNullOrEmpty(r.Password)?r.Content:"",
Attachment = string.IsNullOrEmpty(r.Password)?r.Attachment:"",
Type = r.Type.Name
});
return Ok(result);
}
// GET api/nite/5
[HttpGet("{id}")]
public async Task<IActionResult> Detail(int id,string password)
{
var note = await _noteRespository.GetByIdAsync(id);
if (note == null)
{
return NotFound();
}
if (!string.IsNullOrEmpty(password) && !note.Password.Equals(password))
return Unauthorized();
var result=new NoteViewModel()
{
Id = note.Id,
Tile = note.Tile,
Content = note.Content,
Attachment = note.Attachment,
Type = note.Type.Name
};
return Ok(result);
}
// POST api/note
[HttpPost]
public async Task<IActionResult> Post([FromBody]NoteModel model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
string filename = string.Empty;
await _noteRespository.AddAsync(new Note()
{
Tile = model.Tile,
Content = model.Content,
Create = DateTime.Now,
TypeId = model.Type,
Password = model.Password,
Attachment =filename
});
return CreatedAtAction("Index", "");
}
運行程序,訪問地址http://127.0.0.1:port/api/note 即可獲取note的信息了 當然 也可以訪問地址http://127.0.0.1:port/api/note?pageindex=2 表示獲取第二頁的信息。
講得不詳細的地方,歡迎在博客下方留言或者訪問我的個人網站52dotnet.top與我聯繫。