在ASP.NET CORE MVC中,Web API是其中一個功能子集,可以直接使用MVC的特性及路由等功能。
在成功建構 ASP.NET CORE MVC項目之後,選中解決方案,先填加一個API的檔案夾,填加後,選中API檔案夾,
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuImZzQmZ4MGMiRDMmNzMkZGZhJzNkhTYhBTNyY2YjNWZfdWbp9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.png)
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與我聯系。