ASP.NET Core MVC中构建Web API

时间:2024-01-21 11:05:38

在ASP.NET CORE MVC中,Web API是其中一个功能子集,可以直接使用MVC的特性及路由等功能。

在成功构建 ASP.NET CORE MVC项目之后,选中解决方案,先填加一个API的文件夹,填加后,选中API文件夹,ASP.NET Core MVC中构建Web API

选择新建项,选择填加Web API控制器,要注意控制器在命名时,是以Controller结尾的,这个不能改,前面的随意,比如,此处以NoteController.cs为例

ASP.NET Core MVC中构建Web API

填加后,打开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与我联系。