天天看點

ASP.NET Core MVC中建構Web API

在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與我聯系。

繼續閱讀