第12 屆iT邦幫忙鐵人賽系列文章 (Day19)

Azure Table

Azure Table 是一個具有結構性的 NoSQL 服務,如果資料結構不具備太複雜的關聯關係,透過這種 Key-Value 的方式做儲存,用 JSON 反序列化回來是一個不錯且方便的方式。

註冊 Azure Table 服務

如何註冊一個 Azure Table 服務,可以參考官方文件,建立完成後,可以透過以下路徑取得 Storage 的 Connection String

在 .NET Core Web Api 儲存報名資訊

先從 Nuget 安裝 Microsoft.Azure.Cosmos.Table

新增 AzureTableUtility.cs 並實作

如何透過 SDK 新增 Azure Table

 public static CloudTable CreateTableAsync(string tableName)

    {

    string storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=kylewedding;AccountKey=2mVDAPWt6xZAlxY9xx6pxhzJMvp3vyULGql7PZz9tHEwJ0zc+1vtdt50ZcDwb9I862ez+OoHQGcCkOhU0OvAng==;EndpointSuffix=core.windows.net";

    // Storage 的 連線字串,來源可以用appSetting.json搭配 IOption 注入

    CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(storageConnectionString);

    // 新增 Azure Table

    CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());

    // 不存在則會新增,確認 Table 已存在可使用 await table.CreateIfNotExistsAsync()

    CloudTable table =  tableClient.GetTableReference(tableName);

    return table;

    }

    public static CloudStorageAccount CreateStorageAccountFromConnectionString(string storageConnectionString)

    {

    CloudStorageAccount storageAccount;

    try

    {

    storageAccount = CloudStorageAccount.Parse(storageConnectionString);

    }

    catch (FormatException)

    {

    throw;

    }

    catch (ArgumentException)

    {

    throw;

    }

    return storageAccount;

    }

如何在 Azure Table 新增或更新資料

這邊用泛型,來讓外部決定所要新增的 Model

    public static async Task<ITableEntity> InsertOrMergeEntityAsync<T>(CloudTable table, ITableEntity entity)

    {

    try

    {

    // 新增或更新

    TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

    TableResult result = await table.ExecuteAsync(insertOrMergeOperation);

    var insertedCustomer = result.Result as ITableEntity;

    if (result.RequestCharge.HasValue)

    {

    Console.WriteLine("Request Charge of InsertOrMerge Operation: " + result.RequestCharge);

    }

    return insertedCustomer;

    }

    catch (StorageException e)

    {

    throw;

    }

    }

在 Web Api 新增一個 RegisterController

    [HttpPost]

    public async Task<IActionResult> Post(Users user)

    {

    CloudTable table = AzureTableUtility.CreateTableAsync("Users");

    user.PartitionKey = Guid.NewGuid().ToString("N");

    user.RowKey = Guid.NewGuid().ToString("N");

    var models = await AzureTableUtility.InsertOrMergeEntityAsync<Users>(table, user) as Users;

    return Ok();

    }

User.cs 的內容

這是報名的資料,可以在前一天的 vue.js 實作轉成 C# 的 model

另繼承 TableEntity 來讓 Azure Table SDK 能寫入

    public class Users : TableEntity

    {

    public Users()

    {

    }

    public Users(string _partitionKey, string _rowKey)

    {

    PartitionKey = _partitionKey;

    RowKey = _rowKey;

    }

    public string LineUserId { get; set; }

    public string LineUserName { get; set; }

    public string fullName { get; set; }

    public string phoneNumber { get; set; }

    public int attendEvent { get; set; }

    public int inviteType { get; set; }

    public int relation { get; set; }

    public int attendPeople { get; set; }

    public int child { get; set; }

    public bool speical { get; set; }

    public string message { get; set; }

    }

透過 Postman 測試 Api 即可看到資料能正確寫入

Azure Storage Explorer 登入 Azure帳號並選取 Azure Table 服務即可看到資料

怎麼撈已經寫入的資料呢

新增一個 Get 的 Api

    [HttpGet]

    public async Task<IActionResult> Get()

    {

    CloudTable table = AzureTableUtility.CreateTableAsync("Users");

    List<Users> linqQuery = table

    .CreateQuery<Users>()

    .ToList();

    return Ok(linqQuery);

    }

執行結果,透過這種方式就可以去做一個已報名的後台來瀏覽啦 (本系列文章不會寫到後台)

回到 Vue.js 如何串接

Vue.js 可透過 axios 來跟 Api 溝通

npm install axios --save
  1. 匯入 axios 模組
  2. 將報名表單的發送 post request

如果要打到 local API 可能會有 CORS 跨域問題,可以在主目錄下新增一個 vue.config.js 設定 Proxy

    module.exports = {

    devServer: {

    proxy: {

    '/api': {

    target: 'http://localhost:<Your Local Api Port>',

    changeOrigin: true,

    ws: true,

    pathRewrite: {

    '^api': ''

    }

    }

    }

    }

    }

懶人包,本次學到了什麼?