使用 Visual Studio 2019 實作「RESTful API」

一、介紹

REST 是Roy Thomas Fielding博士於2000年博士論文提出的一種軟體架構風格,目的是讓不同軟體、程式於網路互相傳遞資訊。因為它是一種風格而不是規範,依據筆者的經驗會依照當時的專案或公司規定而決定是否完全遵守。

二、專案架構

圖、Visual Studio 2019 專案架構

三、常用的 HTTP Method 代表用意

  1. GET 讀取
  2. PUT 更新
  3. DELETE 刪除
  4. POST 新增

四、RESTful 路由應用

五、使用 Visual Studio 2019 建置 RESTful API

圖、修改 WebApiConfig.cs

  • 原始碼(C#)
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // 針對 JSON 資料使用 camel 案例。
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = 
            new CamelCasePropertyNamesContractResolver();

        // Web API 設定和服務

        // Web API 路由
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    }
}

六、GET 範例

圖、範例程式碼

  • 原始碼(C#)
[HttpGet]
public Dictionary<string, string> Get(string id = null) 
{
    try
    {
        var mNews = (Dictionary<string, string>)MemoryCache.Default.Get("News");
        if (string.IsNullOrEmpty(id))
        {
            return mNews;
        }
        var ret = new Dictionary<string, string>();
        if (mNews != null)
        {
            ret[id] = mNews[id];
        }

        return ret;
    }
    catch (Exception e) 
    {
        return new Dictionary<string, string>();
    }
}

圖、執行結果

七、POST 範例

圖、範例程式碼

  • 原始碼(C#)
[HttpPost]
public bool Post([FromBody] Dictionary<string, string> news)
{
    try
    {
        var mNews = (Dictionary<string, string>)MemoryCache.Default.Get("News");
        if (mNews == null) 
        {
            mNews = new Dictionary<string, string>();
        }
        foreach (var k in news.Keys)
        {
            mNews[k] = news[k];
        }
        MemoryCache.Default.Set("News", mNews, DateTime.Now.AddMinutes(60));
        return true;
    }
    catch (Exception e)
    {
        return false;
    }
}

圖、執行結果

八、DELETE 範例

圖、範例程式碼

  • 原始碼(C#)
[HttpDelete]
public bool Delete(string id)
{
    try
    {
        var mNews = (Dictionary<string, string>)MemoryCache.Default.Get("News");
        mNews.Remove(id);
        return true;
    }
    catch (Exception e)
    {
        return false;
    }
}

圖、執行結果

九、PUT 範例

圖、範例程式碼

  • 原始碼(C#)
[HttpPut]
public bool Put(string id, [FromBody] Dictionary<string, string> news)
{
    try
    {
        var mNews = (Dictionary<string, string>)MemoryCache.Default.Get("News");
        mNews[id] = news[id];
        MemoryCache.Default.Set("News", mNews, DateTime.Now.AddMinutes(60));
        return true;
    }
    catch (Exception e)
    {
        return false;
    }
}

圖、執行結果

十、相關連結

  1. 使用「Visual Studio 2019」建置一個有 Mvc 和 Web Api 架構的網站
  2. API 測試工具「Postman」

十一、參考

  1. RESTful

留言

這個網誌中的熱門文章

「綠界(Ecpay)」金流介接教學

使用「NLog」來記錄應用程式的大小事吧

使用「ADO.NET」 進行資料庫的讀取、新增、修改、刪除的操作

使用「LINE Messaging API」發送 line 訊息

「Selenium」前端 UI 自動化測試、爬蟲程式 最佳利器

「Katalon Recorder」簡化測試腳本撰寫的工具

如何傳送訊息至「Teams」的 Channel

在Visual Studio 2019 使用 Subversion 的客服端工具「AnkhSVN2019」