iT邦幫忙

2021 iThome 鐵人賽

DAY 2
2
自我挑戰組

.NET Core WebApi網頁應用開發系列 第 2

.Net Core Web Api_筆記02_HTTP資源操作模式GET

在上一篇介紹中我們得知
.net core mvc 跟.net core web api 在專案C#語法跟預設架構差異
得知.net core web api 其實只著重於資料的請求回傳不涉及到View檢視跟View Model相關範疇
因此預設不會幫我們先準備Views跟Models的目錄

基本上於.net core mvc透過GET跟POST就能滿足一般很大宗的CRUD需求
但在web api這邊則是分得更細

今天要介紹的部分是有關於HTTP資源操作共分為如下幾種模式

HttpGet:負責獲得資源

HttpPost:負責資料添加

HttpPut:負責更新資料(約定俗成但也可藉由POST),常用在更新整個資源(比方:整個特定model entity)

HttpDelete:負責刪除資料

HttpHead:獲取HTTP head部分的資訊(通常用void,不需要回傳型態)

HttpOptions:用於獲得自URI的資源在Request/Response過程可使用的功能選項。(可對ajax跨域請求做一些提前檢查),跟HTTP Head有點類似但差異在於會回傳Body內文。

HttpPatch:負責更新資料,常用在更新部分資源(比方:只更新特定model enity中的某些property),使用上ContentType發出請求必須用application/json-patch+json方式而非用form-data(後端會收不到)。

我們上一篇是用範例來測試跑api
這裡我自己額外重新建立一個新的api controller

對Controllers 目錄右鍵新增API控制器
https://ithelp.ithome.com.tw/upload/images/20210902/2010745253PH46V5YY.png

點選加入
命名StudentController.cs
https://ithelp.ithome.com.tw/upload/images/20210902/20107452BSyNkLuhGp.png

新增一個function
若沒特別加特定屬性標籤修飾預設採用HttpGet
在此還是將其標註起來

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyApiTest1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        [HttpGet]
        public string Show()
        {
            return "Hi 你好";
        }

    }
}

在呼叫時直接網址輸入 http://localhost:1914/api/Student
竟然可直接呼叫的到Show方法
https://ithelp.ithome.com.tw/upload/images/20210902/20107452981iZdwgiP.png

原因在於目前api 控制器只存在唯一一個get請求的function
所以會有這種效果

那如果說要指定其方法名來訪問有幾種方式
法1.從Route調整
[Route("api/[controller]/[action]")]
此時呢就無法直接只輸入控制器名來存取的到show方法了
就必須指定show
https://ithelp.ithome.com.tw/upload/images/20210902/20107452942fWqD78I.png

法2.從[HttpGet("[action]")] 來調整
https://ithelp.ithome.com.tw/upload/images/20210902/201074527DP0JNJM4V.png

法3.從[HttpGet("路由任意名稱")] 來設置路由任意名稱(不一定要跟action方法名一致)
比方我這裡設置[HttpGet("Display")]
大小寫沒差

https://ithelp.ithome.com.tw/upload/images/20210902/20107452UbFYwLo2v6.png

如果說我們想要設計一個.net core web api get請求可以
把一個DTO物件(model class)回傳一json格式

再action method回傳型態我們可以透過指定ActionResult<物件型別> 來達成
.net core webapi會自動對於Http Get操作將ActionResult來進行回傳
且會自動把物件序列化為JSON格式的文本

這裡新建一Models目錄並新增如下Person class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyApiTest1.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
    }
}

在StudentController.cs中新增一個action method 如下

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyApiTest1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyApiTest1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        [HttpGet("Display")]
        public string Show()
        {
            return "Hi 你好";
        }

        [HttpGet("GetPerson")]
        public ActionResult<Person> GetPerson()
        {
            var p = new Person
            {
                Id = 1,
                Name = "Jason",
                Age = 27,
                Sex = "man"
            };
            return p;
        }

    }
}

呼叫觀看結果就會看到被自動序列化為 json格式
https://ithelp.ithome.com.tw/upload/images/20210902/20107452XJplDvQt3u.png

而這是單一個物件回傳

當我們想回傳不只一個物件
可能物件List的時候
Action Method設計可以類似如下

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyApiTest1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyApiTest1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        [HttpGet("Display")]
        public string Show()
        {
            return "Hi 你好";
        }

        [HttpGet("GetPerson")]
        public ActionResult<Person> GetPerson()
        {
            var p = new Person
            {
                Id = 1,
                Name = "Jason",
                Age = 27,
                Sex = "man"
            };
            return p;
        }

        [HttpGet("GetPersons")]
        public ActionResult<List<Person>> GetPersons()
        {
            List<Person> lsPersons = new List<Person>()
            {
                new Person(){Id=1,Name="Amy",Age=22,Sex="woman"},
                new Person(){Id=2,Name="Jessica",Age=25,Sex="woman"},
                new Person(){Id=3,Name="Banson",Age=24,Sex="man"}
            };
            return lsPersons;
        }

    }
}

呼叫觀看結果就會看到被自動序列化為 json格式而且是中括號包起來的陣列型態
https://ithelp.ithome.com.tw/upload/images/20210902/20107452NqEUXwCfuv.png

以上是針對HttpGet較常見的處裡也簡單帶一些路由模板概念

本文同步更新至個人部落格
https://coolmandiary.blogspot.com/2021/09/net-core-web-api02.html


上一篇
.Net Core Web Api_筆記01
下一篇
.Net Core Web Api_筆記03_HTTP資源操作模式POST
系列文
.NET Core WebApi網頁應用開發25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言