[Azure雲端服務及應用開發]_SignalR Service創建_利用Azure Functions專案開發Signalr服務程式_part1






由於近期工作專案需要建立類似聊天室留言模組功能和一些推波通知的功能
需要把開發完後的程式佈署到一個穩定可用的託管站點

SignalR技術有點類似  KVM之類的網管切換設備概念
可以提供即時網頁服務


在長期比較下來 Azure SignalR Service是一個比較可穩定佈署for 長期使用的Solution

Azure定價計算機(成本估算)



Step1.選擇左側Create a resource



到輸入框中輸入Signalr過濾Enter查詢







按下Create


大致設置相關操作


Region設置離我們較近的Japan East
Pricing tier 設置為 Free
Service Mode 設置為Serverless

按下Review + Create

放著讓它跑一下






開啟你的Visual Studio Installer
確認Azure相關SDK有裝的


如果沒有安裝就補安裝
安裝好的我們就新增Azure Function專案

一開始找不到的朋友請到Cloud頁簽就能找到了


用 v2 版本
選擇 Http Trigger 
選擇 Storage Emulator
Access Right 改為 Anonymous (這樣任何Client材都能對其發出Request)


預設建好專案模樣


Azure Function程式區塊

 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
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;

namespace KuanyuChat.Functions
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequest req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = new StreamReader(req.Body).ReadToEnd();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
    }
}








回到Azure平台點選Key
複製connection string

貼回local.settings.json檔案中


之後執行
可能會碰到這錯誤


這主要是因為在我們的json設定檔案中default有開啟AzureWebJobsStorage
1
2
3
4
5
6
7
8
9
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME" :  "dotnet",
    "AzureSignalRConnectionString": "\"Endpoint=https://kuanyuchat.service.signalr.net;AccessKe.......";"
  }
}

暫時先移除
只剩下這樣
1
2
3
4
5
6
7
{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME" :  "dotnet",
    "AzureSignalRConnectionString": "\"Endpoint=https://kuanyuchat.service.signalr.net;Ac.....";"
  }
}

之後再執行
會看到很大的閃電就代表有成功Run了




還有呼叫網址


當Azure Function正在以常駐(daemon)方式執行中時候
我們可以嘗試用Postman去測試看看url

當捨麼都不帶去觸發Send時
會回傳提示


當透過GET方式傳送時候的回傳



跟當透過POST方式傳送Json格式資料時的回傳





那我們稍微熟悉了Azure Function的機制後
另外建一個吧



把一開始預設產生的Function1刪除後
新增另一個 Azure Fuction 這裡命名為NegotiateFunction


這裡一樣選Http Trigger




我們刪掉預設帶出來的程式碼
這裡透過Nuget安裝下載Azure SignalR 配套工具
microsoft.azure.webjobs.extensions.signalrservice


遇到報錯可能就先下載Newtonsoft.Json


安裝好的確認

更新
由於一開始用vs2017 遇到很多錯誤
後續改用vs2019就突然順暢無比......(連NewtonJson都不用安裝就能用了)
請大家如有用到統一改用2019

微軟可能有做一些更新


之後程式改寫

 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
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;

namespace KYChat.Functions
{
    public static class NegotiateFunction
    {
        [FunctionName("negotiate")]
        public static SignalRConnectionInfo Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "negotiate/{userId}")] HttpRequest req,
            [SignalRConnectionInfo(HubName = "chat", UserId = "{userId}")] SignalRConnectionInfo connectionInfo,
            ILogger log)
        {
            return connectionInfo;
        }
    }
}


試戳終於正常了







Ref:
快速入門:使用 C# 搭配 Azure Functions 與 SignalR 服務來建立聊天室

使用 Visual Studio 來開發 Azure Functions

Azure Functions 的 SignalR Service 輸入系結

使用 Azure SignalR Service 來開發與設定 Azure Functions


Exception binding parameter 'myEventHubMessage'. Microsoft.Azure.WebJobs.Host: Object reference not set to an instance of an object.

如何解决 Azure Functions ScriptHost initialization failed 错误









留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題