作法:使用入口網站 Web API

在本指南中,您將設定一個網頁和自訂網站範本,這些範本會使用 Web API 從連絡人資料表中讀取、寫入、更新和刪除記錄。

注意

您可以按照此範例中的步驟變更資料列名,或使用其他資料表。

步驟 1。 建立網站設定

您必須先使用入口網站管理應用程式來啟用必要的網站設定,才能使用入口網站 API。 網站設定會根據您要在與 Web API 互動時所使用的資料表而定。

  1. 啟動入口網站管理應用程式

  2. 入口網站管理應用程式的左窗格中,選取網站設定

    在入口網站管理應用程式中開啟網站設定。

  3. 選取新增

  4. 名稱方塊中,輸入 Webapi/contact/enabled

  5. 網站清單中,選取您的網站記錄。

  6. 方塊中,輸入 true

    啟用 WebAPI 網站設定的連絡人資料表。

  7. 選取儲存後關閉

  8. 選取新增

  9. 名稱方塊中,輸入 Webapi/contact/fields

  10. 網站清單中,選取您的網站記錄。

  11. 方塊中,輸入
    firstname,lastname,fullname,emailaddress1,telephone1

    啟用 Web API 連絡人資料表欄位網站設定。

  12. 選取儲存後關閉

  13. 選取新增

  14. 名稱方塊中,輸入 Webapi/error/innererror

    啟用 Web API 內部錯誤網站設定。

  15. 網站清單中,選取您的網站記錄。

  16. 方塊中,輸入 true

  17. 選取儲存後關閉

  18. 驗證 Web API 的網站設定。

步驟 2: 設定權限

您必須設定權限,才能讓使用者使用 Web API 功能。 在此範例中,您需要設定或建立使用 Web API 的新 Web 角色,接下來新增連絡人資料表的資料表權限,並將資料表權限關聯至 Web 角色,最後將 Web 角色指派給使用者,以允許他們使用 Web API。

注意

Web API 會遵循來自已驗證使用者或匿名 Web 角色的 Web 角色內容的資料表權限。 考慮您的使用者是否已具有可存取 Web API 所需網站中特定資料表的 Web 角色。 您不需要為了使用 Web API 而建立其他的 Web 角色。

建立 Web 角色

如果您目前沒有透過 Web API 存取資料表的 Web 角色,或需要不同的資料存取內容,請按照以下步驟建立新的 Web 角色並指派資料表權限。

  1. 啟動入口網站管理應用程式

  2. 在左窗格的安全性區段中,選取 Web 角色

  3. 選取新增

  4. 名稱方塊中,輸入 Web API 使用者 (或任何最能反映存取此功能使用者角色的名稱)。

  5. 網站清單中,選取您的網站記錄。

    新增 Web API 使用者 Web 角色。

  6. 選取儲存

建立資料表權限

  1. 啟動 Power Pages 設計工作室

  2. 選取設定工作區。

  3. 安全性區段下方,選取資料表權限

  4. 選取新權限

  5. 名稱方塊中,輸入連絡人資料表權限

  6. 資料表名稱清單中,選取連絡人 (連絡人)

  7. 存取模式清單中,選取全域

  8. 選取讀取寫入建立刪除權限。

  9. 選取 + 新增角色,然後選取先前所選取或建立的 Web 角色

  10. 選取儲存並關閉

    連絡人資料表權限。

將連絡人新增至 Web 角色

  1. 啟動入口網站管理應用程式

  2. 在左窗格的安全性區段中,選取連絡人

  3. 選擇要在此範例中用於 Web API 的連絡人。

    注意

    此連絡人是此範例中用來測試 Web API 的使用者帳戶。 請務必在您的入口網站中選取正確的連絡人。

  4. 選取相關>Web 角色

    選取相關 Web 角色。

  5. 選取新增現有 Web 角色

  6. 選取先前建立的 WEB API 使用者角色。

  7. 選取新增

    Web 角色相關檢視表。

  8. 選取儲存後關閉

步驟 3: 建立網頁

現在您已啟用 Web API 並已設定使用者權限,請建立含範例程式碼的網頁,以查看、編輯、建立及刪除記錄。

  1. 啟動 Power Pages 設計工作室

  2. 頁面工作區中,選取 + 頁面

  3. 新增頁面對話方塊中,

  4. 名稱中,輸入 WebAPI,並選取從空白開始配置。

  5. 選取新增

  6. 選取右上角的編輯程式碼選項。

  7. 選取開啟 Visual Studio Code

  8. 複製下列範例程式碼片段,並在頁面區段的 <div></div> 標籤之間將其貼上。

        <!-- Sample code for Web API demonstration -->
    <style>
        #processingMsg {
            width: 150px;
            text-align: center;
            padding: 6px 10px;
            z-index: 9999;
            top: 0;
            left: 40%;
            position: fixed;
            -webkit-border-radius: 0 0 2px 2px;
            border-radius: 0 0 2px 2px;
            -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            display: none;
        }
    
        table td[data-attribute] .glyphicon-pencil {
            margin-left: 5px;
            opacity: 0;
        }
    
        table td[data-attribute]:hover .glyphicon-pencil {
            opacity: 0.7;
        }
    </style>
    
    <script>
      $(function() {
        //Web API ajax wrapper
        (function(webapi, $) {
          function safeAjax(ajaxOptions) {
            var deferredAjax = $.Deferred();
            shell.getTokenDeferred().done(function(token) {
              // Add headers for ajax
              if (!ajaxOptions.headers) {
                $.extend(ajaxOptions, {
                  headers: {
                    "__RequestVerificationToken": token
                  }
                });
              } else {
                ajaxOptions.headers["__RequestVerificationToken"] = token;
              }
              $.ajax(ajaxOptions)
                .done(function(data, textStatus, jqXHR) {
                  validateLoginSession(data, textStatus, jqXHR, deferredAjax.resolve);
                }).fail(deferredAjax.reject); //ajax
            }).fail(function() {
              deferredAjax.rejectWith(this, arguments); // On token failure pass the token ajax and args
            });
            return deferredAjax.promise();
          }
          webapi.safeAjax = safeAjax;
        })(window.webapi = window.webapi || {}, jQuery)
        // Notification component
        var notificationMsg = (function() {
          var $processingMsgEl = $('#processingMsg'),
            _msg = 'Processing...',
            _stack = 0,
            _endTimeout;
          return {
            show: function(msg) {
              $processingMsgEl.text(msg || _msg);
              if (_stack === 0) {
                clearTimeout(_endTimeout);
                $processingMsgEl.show();
              }
              _stack++;
            },
            hide: function() {
              _stack--;
              if (_stack <= 0) {
                _stack = 0;
                clearTimeout(_endTimeout);
                _endTimeout = setTimeout(function() {
                  $processingMsgEl.hide();
                }, 500);
              }
            }
          }
        })();
        // Inline editable table component
        var webAPIExampleTable = (function() {
          var trTpl = '<% _.forEach(data, function(data){ %>' +
            '<tr data-id="<%=data.id%>" data-name="<%=data.fullname%>">' +
            '<% _.forEach(columns, function(col){ %>' +
            '<td data-attribute="<%=col.name%>" data-label="<%=col.label%>" data-value="<%=data[col.name]%>">' +
            '<%-data[col.name]%><i class="glyphicon glyphicon-pencil"></i>' +
            '</td>' +
            '<% }) %>' +
            '<td>' +
            '<button class="btn btn-default delete" type="submit"><i class="glyphicon glyphicon-trash" aria-hidden="true"></i></button>' +
            '</td>' +
            '</tr>' +
            '<% }) %>';
          var tableTpl = '<table class="table table-hover">' +
            '<thead>' +
            '<tr>' +
            '<% _.forEach(columns, function(col){ %>' +
            '<th><%=col.label%></th>' +
            '<% }) %>' +
            '<th>' +
            '<button class="btn btn-default add" type="submit">' +
            '<i class="glyphicon glyphicon-plus" aria-hidden="true"></i> Add Sample Record' +
            '</button>' +
            '</th>' +
            '</tr>' +
            '</thead>' +
            '<tbody>' + trTpl + '</tbody>' +
            '</table>';
          function getDataObject(rowEl) {
            var $rowEl = $(rowEl),
              attrObj = {
                id: $rowEl.attr('data-id'),
                name: $rowEl.attr('data-name')
              };
            $rowEl.find('td').each(function(i, el) {
              var $el = $(el),
                key = $el.attr('data-attribute');
              if (key) {
                attrObj[key] = $el.attr('data-value');
              }
            })
            return attrObj;
          }
          function bindRowEvents(tr, config) {
            var $row = $(tr),
              $deleteButton = $row.find('button.delete'),
              dataObj = getDataObject($row);
            $.each(config.columns, function(i, col) {
              var $el = $row.find('td[data-attribute="' + col.name + '"]');
              $el.on('click', $.proxy(col.handler, $el, col, dataObj));
            });
            //User can delete record using this button
            $deleteButton.on('click', $.proxy(config.deleteHandler, $row, dataObj));
          }
          function bindTableEvents($table, config) {
            $table.find('tbody tr').each(function(i, tr) {
              bindRowEvents(tr, config);
            });
            $table.find('thead button.add').on('click', $.proxy(config.addHandler, $table));
          }
          return function(config) {
            var me = this,
              columns = config.columns,
              addHandler = config.addHandler,
              deleteHandler = config.deleteHandler,
              $table;
            me.render = function(el) {
              $table = $(el).html(_.template(tableTpl)({
                columns: columns,
                data: me.data
              })).find('table');
              bindTableEvents($table, {
                columns: columns,
                addHandler: addHandler,
                deleteHandler: deleteHandler
              });
            }
            me.addRecord = function(record) {
              $table.find('tbody tr:first').before(_.template(trTpl)({
                columns: columns,
                data: [record]
              }));
              bindRowEvents($table.find('tbody tr:first'), config);
            }
            me.updateRecord = function(attributeName, newValue, record) {
              $table.find('tr[data-id="' + record.id + '"] td[data-attribute="' + attributeName + '"]').text(newValue);
            }
            me.removeRecord = function(record) {
              $table.find('tr[data-id="' + record.id + '"]').fadeTo("slow", 0.7, function() {
                $(this).remove();
              });
            }
          };
        })();
        //Applicaton ajax wrapper 
        function appAjax(processingMsg, ajaxOptions) {
          notificationMsg.show(processingMsg);
          return webapi.safeAjax(ajaxOptions)
            .fail(function(response) {
              if (response.responseJSON) {
                alert("Error: " + response.responseJSON.error.message)
              } else {
                alert("Error: Web API is not available... ")
              }
            }).always(notificationMsg.hide);
        }
        function loadRecords() {
          return appAjax('Loading...', {
            type: "GET",
            url: "/_api/contacts?$select=fullname,firstname,lastname,emailaddress1,telephone1",
            contentType: "application/json"
          });
        }
        function addSampleRecord() {
          //Sample data to create a record - change as appropriate
          var recordObj = {
            firstname: "Willie",
            lastname: "Huff" + _.random(100, 999),
            emailaddress1: "Willie.Huff@contoso.com",
            telephone1: "555-123-4567"
          };
          appAjax('Adding...', {
            type: "POST",
            url: "/_api/contacts",
            contentType: "application/json",
            data: JSON.stringify(recordObj),
            success: function(res, status, xhr) {
              recordObj.id = xhr.getResponseHeader("entityid");
              recordObj.fullname = recordObj.firstname + " " + recordObj.lastname;
              table.addRecord(recordObj);
            }
          });
          return false;
        }
        function deleteRecord(recordObj) {
          var response = confirm("Are you sure, you want to delete \"" + recordObj.name + "\" ?");
          if (response == true) {
            appAjax('Deleting...', {
              type: "DELETE",
              url: "/_api/contacts(" + recordObj.id + ")",
              contentType: "application/json",
              success: function(res) {
                table.removeRecord(recordObj);
              }
            });
          }
          return false;
        }
        function updateRecordAttribute(col, recordObj) {
          var attributeName = col.name,
            value = recordObj[attributeName],
            newValue = prompt("Please enter \"" + col.label + "\"", value);
          if (newValue != null && newValue !== value) {
            appAjax('Updating...', {
              type: "PUT",
              url: "/_api/contacts(" + recordObj.id + ")/" + attributeName,
              contentType: "application/json",
              data: JSON.stringify({
                "value": newValue
              }),
              success: function(res) {
                table.updateRecord(attributeName, newValue, recordObj);
              }
            });
          }
          return false;
        }
        var table = new webAPIExampleTable({
          columns: [{
            name: 'firstname',
            label: 'First Name',
            handler: updateRecordAttribute
          }, {
            name: 'lastname',
            label: 'Last Name',
            handler: updateRecordAttribute
          }, {
            name: 'emailaddress1',
            label: 'Email',
            handler: updateRecordAttribute
          }, {
            name: 'telephone1',
            label: 'Telephone',
            handler: updateRecordAttribute
          }],
          data: [],
          addHandler: addSampleRecord,
          deleteHandler: deleteRecord
        });
        loadRecords().done(function(data) {
          table.data = _.map(data.value, function(record){
            record.id = record.contactid;
            return record;
          });
          table.render($('#dataTable'));
        });
      });
    </script>
    <div id="processingMsg" class="alert alert-warning" role="alert"></div>
    <div id="dataTable"></div>
    

    貼上程式碼。

  9. 選取 CTRL-S 以儲存變更。

  10. 在設計工作室中,選取同步以使用程式碼編輯更新網站。

步驟 4. 使用 Web API 讀取、查看、編輯、建立和刪除

若要測試 Web API 功能:

  1. 選取預覽版,然後選擇桌面

  2. 使用已獲指派您先前所建立之 Web API 使用者角色的使用者帳戶來登入您的網站。

  3. 移至先前建立的 WebApi 網頁。

    範例 webapi 網頁。

  4. 選取新增範例記錄,以透過指令碼新增範例記錄。

  5. 選取一個欄位。 在此範例中,我們選取電子郵件來變更連絡人的電子郵件地址。

    編輯電子郵件

  6. 選取刪除圖示以永久刪除記錄。

現在,您已經建立一個包含讀取、編輯、建立和刪除記錄範例的網頁,您可以自訂表單和版面配置。

下一個步驟

編寫 HTTP 要求並處理錯誤

另請參閱