使用C#開發LINE Bot(31) – .net core 2.2 Web範例

一路上都有不少朋友問過:『LineBotSDK怎麼還不支援 .net core呢?』 我總是回答『手邊事情太多,一直沒時間啊…』不過,老是跟人說:『你永遠有時間做你認為重要的事…』我自己卻拿沒時間當藉口,似乎有點牽強…

該怎麼說呢,總之,我覺得目前看起來, .net core 2.2 似乎是一個挺好的起跑點,所以,我們準備全面開始支援 .net core囉。

SDK

關於LineBotSDK的 .net core套件,前幾天已經跟朋友們介紹過了,我們剛更新了一個 beta3 的版本,幾乎已經可以當作正式版使用了,nuget package 可以參考底下網址:
https://www.nuget.org/packages/LineBotSDK/2.0.0-beta3

這包package可以直接支援 .net framework 與 .net core,所以不管你用哪一種開發技術(只要是 .net)你都只需要直接引用就好。所有的API都在同樣的namespace底下,如果你想把source code從WebForm轉成 .net core,也完全不用改API的用法。

razor page 範例

很久以前我就說過,上了 .net core之後,我自己大部分的專案選擇用razor pages來開發Web專案(少部分用 .net core mvc,箇中原因有機會再慢慢談,不過,.net core的WebAPI依舊是要的),所以,底下這個部分我們會直接介紹一個使用 .net core 2.2 razor pages開發以及透過 .net core WebAPI來做LINE Bot WebHook的範例。

不管你用的是MAC或是PC,不管使用VS 2019或VS Code,你都可以直接在command line底下建立一個資料夾,然後執行底下指令,clone github上的專案…

git clone https://github.com/isdaviddong/LineBotSdkDotNetCoreWebExample.git

當然,別跟我說你沒安裝 Git 和 dotnet SDK

執行後你應該會看到類似底下這樣的輸出:

Cloning into 'LineBotSdkDotNetCoreWebExample'...
remote: Enumerating objects: 29, done.
remote: Counting objects: 100% (29/29), done.
remote: Compressing objects: 100% (25/25), done.
remote: Total 29 (delta 6), reused 22 (delta 3), pack-reused 0
Unpacking objects: 100% (29/29), done.
Checking connectivity... done.

接著,請用底下指令進入到包含 .sln 的資料夾

cd LineBotSdkDotNetCoreWebExample
cd main

然後執行底下指令(請確定您有安裝 .net sdk 2.2)

dotnet build

你應該會看類似底下這樣的回應:

Microsoft (R) Build Engine for .NET Core 15.9.20+g88f5fadfbe 版
Copyright (C) Microsoft Corporation. 著作權所有,並保留一切權利。

  正在還原 D:\test\linebottest\LineBotSdkDotNetCoreWebExample\main\main\main.csproj 的封裝...
  正在安裝 System.Composition.TypedParts 1.0.31。
  正在安裝 System.Composition.Convention 1.0.31。
  正在安裝 System.Composition.Runtime 1.0.31。
  正在安裝 System.Composition.AttributedModel 1.0.31。
  正在安裝 System.Composition.Hosting 1.0.31。
  正在安裝 System.Composition 1.0.31。
  正在安裝 System.Linq.Parallel 4.3.0。
  正在安裝 Microsoft.CodeAnalysis.Workspaces.Common 2.8.0。
  正在安裝 Microsoft.CodeAnalysis.CSharp.Workspaces 2.8.0。
  正在安裝 Microsoft.VisualStudio.Web.CodeGeneration.Design 2.2.3。
  正在安裝 Newtonsoft.Json 12.0.2。
  正在安裝 Microsoft.VisualStudio.Web.CodeGenerators.Mvc 2.2.3。
  正在安裝 NuGet.Frameworks 4.7.0。
  正在安裝 Microsoft.VisualStudio.Web.CodeGeneration 2.2.3。
  正在安裝 Microsoft.VisualStudio.Web.CodeGeneration.Contracts 2.2.3。
  正在安裝 Microsoft.VisualStudio.Web.CodeGeneration.Utils 2.2.3。
  正在安裝 Microsoft.VisualStudio.Web.CodeGeneration.Templating 2.2.3。
  正在安裝 Microsoft.VisualStudio.Web.CodeGeneration.Core 2.2.3。
  正在安裝 Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore 2.2.3。
  正在安裝 LineBotSDK 2.0.0-beta3。
  正在產生 MSBuild 檔案 D:\test\linebottest\LineBotSdkDotNetCoreWebExample\main\main\obj\main.csproj.nuget.g.props。
  正在產生 MSBuild 檔案 D:\test\linebottest\LineBotSdkDotNetCoreWebExample\main\main\obj\main.csproj.nuget.g.targets。
  D:\test\linebottest\LineBotSdkDotNetCoreWebExample\main\main\main.csproj 的還原於 32.02 sec 完成。
  main -> D:\test\linebottest\LineBotSdkDotNetCoreWebExample\main\main\bin\Debug\netcoreapp2.2\main.dll
  main -> D:\test\linebottest\LineBotSdkDotNetCoreWebExample\main\main\bin\Debug\netcoreapp2.2\main.Views.dll

建置成功。
    0 個警告
    0 個錯誤

經過時間 00:00:47.74

完成後,接著可以用底下指令進入到包含 .csproj 的資料夾

cd main

然後執行

dotnet run

如果沒有意外,你應該會看到底下回應

Hosting environment: Production
Content root path: D:\test\linebottest\LineBotSdkDotNetCoreWebExample\main\main
Now listening on: http://localhost:5000
Now listening on: https://localhost:5001
Application started. Press Ctrl+C to shut down.

這時候你就可以開啟browser,輸入 http://localhost:5000
會看到底下網頁:

只需要在上面輸入你的 channel access token 與 userID,就可以測試發訊息給特定 user囉…

Razor Pages

.net core 的Razor Pages Web專案我們將主程式碼放在 Pages資料夾底下的 index.cshtml與index.cshtml.cs。先來看index.cshtml的部分:

<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script>
    </script>
</head>
<body>
    <h3>LINE Bot - Send Message Test</h3>
    <div class="row" style="margin:10px">
        <div class="col-12">
            <form method="POST">
                @Html.AntiForgeryToken()
                <div class="card">
                    <div class="card-body">
                        <label>LINE Bot Channel Access Token:</label>
                        <textarea class="form-control" name="txbToken" rows="2">@Model.txbToken</textarea>
                        <label>To User ID:</label>
                        <input class="form-control" name="txbUserId" value="@Model.txbUserId" />
                        <div class="row">
                            <div class="col-6">
                                <label>Message:</label>
                                <input class="form-control" name="txbMessage" value="@Model.txbMessage" />
                                <button type="submit" asp-page-handler="SendMessage">Send Message</button>
                            </div>
                            <div class="col-6">
                                <label>sticker:</label>
                                <input class="form-control" name="txbStickerPkgId" value="@Model.txbStickerPkgId" />
                                <input class="form-control" name="txbStickerStkId" value="@Model.txbStickerStkId" />
                                <button type="submit" asp-page-handler="SendSticker">Send Sticker</button>
                            </div>
                            <label>
                                RESULT (JSON) :  @Model.result
                            </label>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</body>
</html>

在razor pages裡面,大部分程式碼都是很單純的HTML,無需太多解釋,只有 27 和 33行的兩個Submit Button,我們用到了 .net core razor 的 asp-page-handler 這個attribute。這個attribute它會讓按鈕觸發後端相對應的OnPost_____() 方法,所以你會看到我們後端的程式碼是這樣寫的…

        public void OnPostSendMessage()
        {
            if (string.IsNullOrEmpty(txbToken) ||
                string.IsNullOrEmpty(txbUserId) ||
                string.IsNullOrEmpty(txbMessage))
            {
                this.result = "cannot push message due to missing information...";
            }
            else
            {
                var bot = new isRock.LineBot.Bot(this.txbToken);

                var ret = bot.PushMessage(this.txbUserId, this.txbMessage);
                this.result = ret;
            }
        }
        
        public void OnPostSendSticker()
        {
            if (string.IsNullOrEmpty(txbToken) ||
                    string.IsNullOrEmpty(txbUserId))
            {
                this.result = "missing data...";
            }
            else
            {
                var bot = new isRock.LineBot.Bot(this.txbToken);

                var ret = bot.PushMessage(
                    this.txbUserId,
                    new isRock.LineBot.StickerMessage(this.txbStickerPkgId, this.txbStickerStkId)
                    );
                this.result = ret;
            }
            return;
        }

第1行和第18行的兩個method,分別對應到前端button按下後的功能,你會發現裡面就是很單純的透過LineBotSDK來發送訊息,如此這般,就完成囉…

關於WebHook

這個範例不只支援訊息發送,當然還有訊息的接收,我們先把sample code放在GitHub分享給大家了,下一篇我們再來談談 WebHook 的部分…

-----------
最新實體課程:http://www.studyhost.tw/NewCourses/LineBot
線上課程:https://www.udemy.com/line-bot/
電子書:http://studyhost.blogspot.tw/2017/12/line-bot.html
LineBotSDK:https://www.nuget.org/packages/LineBotSDK
如果需要即時取得更多相關訊息,可按這裡加入FB專頁。若這篇文章對您有所幫助,請幫我們分享出去,謝謝您的支持。

留言

這個網誌中的熱門文章

使用 Airtable 在小型需求上取代傳統資料庫

精彩(且驚人)的Semantic Kernel入門範例

使用Semantic Kernel 建立自然語言請假系統

在 LINE Bot 開發中使用Semantic Kernel建立自然語言請假系統

專業的價值...