我是靠谱客的博主 害羞皮带,这篇文章主要介绍ASP.NET Core MVC中构建Web API,现在分享给大家,希望可以做个参考。

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

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

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

填加后,打开NoteController.cs,系统已经帮我们构建好了一些基础的功能,我们需要在其基础上进行一些个性化修改使其成为我们自己的代码。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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与我联系。

最后

以上就是害羞皮带最近收集整理的关于ASP.NET Core MVC中构建Web API的全部内容,更多相关ASP.NET内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部