教學課程:在 Azure App Service 中裝載具有 CORS 支援的 RESTful APITutorial: Host a RESTful API with CORS in Azure App Service

Azure App Service 可提供可高度擴充、自我修復的 Web 主控服務。Azure App Service provides a highly scalable, self-patching web hosting service. 此外,App Service 有 RESTful API 的內建跨原始資源共用 (CORS) 支援。In addition, App Service has built-in support for Cross-Origin Resource Sharing (CORS) for RESTful APIs. 本教學課程示範如何將 ASP.NET Core API 應用程式部署至具有 CORS 支援的 App Service。This tutorial shows how to deploy an ASP.NET Core API app to App Service with CORS support. 您可使用命令列工具來設定應用程式,以及使用 Git 部署應用程式。You configure the app using command-line tools and deploy the app using Git.

在本教學課程中,您了解如何:In this tutorial, you learn how to:

  • 使用 Azure CLI 建立 App Service 資源Create App Service resources using Azure CLI
  • 使用 Git 將 RESTful API 部署到 AzureDeploy a RESTful API to Azure using Git
  • 啟用 App Service CORS 支援Enable App Service CORS support

您可以在 macOS、Linux、Windows 上依照本教學課程中的步驟進行。You can follow the steps in this tutorial on macOS, Linux, Windows.

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.


若要完成本教學課程:To complete this tutorial:

建立本機 ASP.NET Core 應用程式Create local ASP.NET Core app

在此步驟中,您要設定本機 ASP.NET Core 專案。In this step, you set up the local ASP.NET Core project. App Service 會對以其他語言撰寫的 API 支援相同的工作流程。App Service supports the same workflow for APIs written in other languages.

複製範例應用程式Clone the sample application

在終端機視窗中,使用 cd 移至工作目錄。In the terminal window, cd to a working directory.

執行下列命令來複製範例存放庫。Run the following command to clone the sample repository.

git clone https://github.com/Azure-Samples/dotnet-core-api

此存放庫包含根據下列教學課程建立的應用程式:使用 Swagger 的 ASP.NET Core Web API 說明頁面This repository contains an app that's created based on the following tutorial: ASP.NET Core Web API help pages using Swagger. 它會使用 Swagger 產生器來提供 Swagger UI和 Swagger JSON 端點。It uses a Swagger generator to serve the Swagger UI and the Swagger JSON endpoint.

執行應用程式Run the application

執行下列命令以安裝必要的套件、執行資料庫移轉,然後啟動應用程式。Run the following commands to install the required packages, run database migrations, and start the application.

cd dotnet-core-api
dotnet restore
dotnet run

在瀏覽器中瀏覽至 http://localhost:5000/swagger 以使用 Swagger UI 播放。Navigate to http://localhost:5000/swagger in a browser to play with the Swagger UI.

在本機執行的 ASP.NET Core API

瀏覽至 http://localhost:5000/api/todo 並查看 ToDo JSON 項目清單。Navigate to http://localhost:5000/api/todo and see a list of ToDo JSON items.

瀏覽至 http://localhost:5000 並使用瀏覽器應用程式播放。Navigate to http://localhost:5000 and play with the browser app. 稍後,您會將瀏覽器應用程式指向 App Service 中的遠端 API,以測試 CORS 功能。Later, you will point the browser app to a remote API in App Service to test CORS functionality. 瀏覽器應用程式的程式碼位於存放庫的 wwwroot 目錄中。Code for the browser app is found in the repository's wwwroot directory.

如需隨時停止 ASP.NET Core,請在終端機上按下 Ctrl+CTo stop ASP.NET Core at any time, press Ctrl+C in the terminal.

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,可在瀏覽器中使用。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. Cloud Shell 可讓您使用 bashPowerShell 以與 Azure 服務搭配使用。Cloud Shell lets you use either bash or PowerShell to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文提到的程式碼,而不必在本機環境上安裝任何工具。You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

若要啟動 Azure Cloud Shell:To launch Azure Cloud Shell:

選項Option 範例/連結Example/Link
選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 選取 [試用] 並不會自動將程式碼複製到 Cloud Shell 中。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的試試看範例
請前往 https://shell.azure.com 或選取 [啟動 Cloud Shell] 按鈕,在瀏覽器中開啟 Cloud Shell。Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新視窗中啟動 Cloud ShellLaunch Cloud Shell in a new window
選取 Azure 入口網站右上角功能表列中的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 入口網站中的 [Cloud Shell] 按鈕

若要在 Azure Cloud Shell 中執行本文中的程式碼:To run the code in this article in Azure Cloud Shell:

  1. 啟動 Cloud Shell。Launch Cloud Shell.
  2. 選取程式碼區塊上的 [複製] 按鈕,複製程式碼。Select the Copy button on a code block to copy the code.
  3. 在 Windows 和 Linux 上按 Ctrl+Shift+V;或在 macOS 上按 Cmd+Shift+V,將程式碼貼到 Cloud Shell工作階段中。Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.
  4. 按下 Enter 鍵執行程式碼。Press Enter to run the code.

將應用程式部署到 AzureDeploy app to Azure

在此步驟中,您會將與 SQL Database 連線的 .NET Core 應用程式部署至 App Service。In this step, you deploy your SQL Database-connected .NET Core application to App Service.

設定本機 git 部署Configure local git deployment

FTP 和本機 Git 可以透過使用「部署使用者」 部署到 Azure Web 應用程式。FTP and local Git can deploy to an Azure web app by using a deployment user. 部署使用者只需設定一次,就能供所有 Azure 部署使用。Once you configure your deployment user, you can use it for all your Azure deployments. 使用者名稱和密碼屬於帳戶等級部署,因此與 Azure 訂用帳戶認證不同。Your account-level deployment username and password are different from your Azure subscription credentials.

若要設定部署使用者,請在 Azure Cloud Shell 中執行 az webapp deployment user set 命令。To configure the deployment user, run the az webapp deployment user set command in Azure Cloud Shell. 以部署使用者的使用者名稱和和密碼來取代「username」<<和「password」。Replace <username> and <password> with a deployment user username and password.

  • 使用者名稱在 Azure 服務及本機 Git 推送中都必須是唯一的,且不能包含 ‘@’ 符號。The username must be unique within Azure, and for local Git pushes, must not contain the ‘@’ symbol.
  • 密碼長度必須至少為 8 個字元,包含下列三個元素其中兩個:字母、數字及符號。The password must be at least eight characters long, with two of the following three elements: letters, numbers, and symbols.
az webapp deployment user set --user-name <username> --password <password>

JSON 輸出會將密碼顯示為 nullThe JSON output shows the password as null. 如果您收到 'Conflict'. Details: 409 錯誤,請變更使用者名稱。If you get a 'Conflict'. Details: 409 error, change the username. 如果您收到 'Bad Request'. Details: 400 錯誤,請使用更強的密碼。If you get a 'Bad Request'. Details: 400 error, use a stronger password.

將使用者名稱和密碼記錄下來,在部署 Web 應用程式時還會用到。Record your username and password to use to deploy your web apps.

建立資源群組Create a resource group

資源群組是一個邏輯容器,可在其中部署與管理 Azure 資源 (例如 Web 應用程式、資料庫和儲存體帳戶)。A resource group is a logical container into which Azure resources like web apps, databases, and storage accounts are deployed and managed. 例如,您可以選擇在稍候透過一個簡單的步驟刪除整個資源群組。For example, you can choose to delete the entire resource group in one simple step later.

在 Cloud Shell 中,使用 az group create 命令來建立資源群組。In the Cloud Shell, create a resource group with the az group create command. 下列範例會在「西歐」 位置建立名為 myResourceGroup 的資源群組。The following example creates a resource group named myResourceGroup in the West Europe location. 若要查看免類層中 App Service 的所有支援位置,請執行 az appservice list-locations --sku FREE 命令。To see all supported locations for App Service in Free tier, run the az appservice list-locations --sku FREE command.

az group create --name myResourceGroup --location "West Europe"

您通常會在附近的區域中建立資源群組和資源。You generally create your resource group and the resources in a region near you.

當命令完成時,JSON 輸出會顯示資源群組屬性。When the command finishes, a JSON output shows you the resource group properties.

建立應用程式服務方案Create an App Service plan

在 Cloud Shell 中,使用 az appservice plan create 命令來建立 App Service 方案。In the Cloud Shell, create an App Service plan with the az appservice plan create command.

下列範例會在免費定價層中建立名為 myAppServicePlan 的 App Service 方案。The following example creates an App Service plan named myAppServicePlan in the Free pricing tier:

az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku FREE

建立 App Service 方案後,Azure CLI 會顯示類似下列範例的資訊:When the App Service plan has been created, the Azure CLI shows information similar to the following example:

  "adminSiteName": null,
  "appServicePlanName": "myAppServicePlan",
  "geoRegion": "West Europe",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "app",
  "location": "West Europe",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  < JSON data removed for brevity. >
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null

建立 Web 應用程式Create a web app

myAppServicePlan App Service 方案中建立 Web 應用程式Create a web app in the myAppServicePlan App Service plan.

在 Cloud Shell 中,您可以使用 az webapp create 命令。In the Cloud Shell, you can use the az webapp create command. 在下列範,了中,使用全域唯一的應用程式名稱 (有效的字元為 a-z0-9-) 取代 <app-name>In the following example, replace <app-name> with a globally unique app name (valid characters are a-z, 0-9, and -).

az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --deployment-local-git

建立 Web 應用程式後,Azure CLI 會顯示類似下列範例的輸出:When the web app has been created, the Azure CLI shows output similar to the following example:

Local git is configured with url of 'https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git'
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "<app-name>.azurewebsites.net",
  "deploymentLocalGitUrl": "https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git",
  "enabled": true,
  < JSON data removed for brevity. >


Git 遠端的 URL 會顯示在 deploymentLocalGitUrl 屬性中,其格式為 https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.gitThe URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git. 儲存此 URL,稍後您會用到此資訊。Save this URL as you need it later.

從 Git 推送至 AzurePush to Azure from Git

回到「本機終端視窗」 ,將 Azure 遠端新增至本機 Git 存放庫。Back in the local terminal window, add an Azure remote to your local Git repository. <deploymentLocalGitUrl-from-create-step> 取代為您從建立 Web 應用程式儲存之 Git 遠端的 URL。Replace <deploymentLocalGitUrl-from-create-step> with the URL of the Git remote that you saved from Create a web app.

git remote add azure <deploymentLocalGitUrl-from-create-step>

推送到 Azure 遠端,使用下列命令來部署您的應用程式。Push to the Azure remote to deploy your app with the following command. 當 Git 認證管理員提示輸入認證時,請務必輸入您在 [設定部署使用者] 中建立的認證,而不是您用來登入 Azure 入口網站的認證。When prompted for credentials by Git Credential Manager, make sure that you enter the credentials you created in Configure a deployment user, not the credentials you use to sign in to the Azure portal.

git push azure master

此命令可能會花數分鐘執行。This command may take a few minutes to run. 執行上述命令時,會顯示類似下列範例的資訊:While running, it displays information similar to the following example:

Counting objects: 98, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (92/92), done.
Writing objects: 100% (98/98), 524.98 KiB | 5.58 MiB/s, done.
Total 98 (delta 8), reused 0 (delta 0)
remote: Updating branch 'master'.
remote: .
remote: Updating submodules.
remote: Preparing deployment for commit id '0c497633b8'.
remote: Generating deployment script.
remote: Project file path: ./DotNetCoreSqlDb.csproj
remote: Generated deployment script files
remote: Running deployment command...
remote: Handling ASP.NET Core Web Application deployment.
remote: .
remote: .
remote: .
remote: Finished successfully.
remote: Running post deployment command(s)...
remote: Deployment successful.
remote: App container will begin restart within 10 seconds.
To https://<app_name>.scm.azurewebsites.net/<app_name>.git
 * [new branch]      master -> master

瀏覽至 Azure 應用程式Browse to the Azure app

在瀏覽器中瀏覽至 http://<app_name>.azurewebsites.net/swagger 並使用 Swagger UI 播放。Navigate to http://<app_name>.azurewebsites.net/swagger in a browser and play with the Swagger UI.

在 Azure App Service 中執行的 ASP.NET Core API

瀏覽至 http://<app_name>.azurewebsites.net/swagger/v1/swagger.json 以查看您已部署 API 的 swagger.json 。Navigate to http://<app_name>.azurewebsites.net/swagger/v1/swagger.json to see the swagger.json for your deployed API.

瀏覽至 http://<app_name>.azurewebsites.net/api/todo 以查看您已部署的 API 是否能運作。Navigate to http://<app_name>.azurewebsites.net/api/todo to see your deployed API working.

新增 CORS 功能Add CORS functionality

接著,您會在 App Service 中為 API 啟用內建 CORS 支援。Next, you enable the built-in CORS support in App Service for your API.

在範例應用程式中測試 CORSTest CORS in sample app

在您的本機存放庫中,開啟 wwwroot/index.html 。In your local repository, open wwwroot/index.html.

在第 51 行中,將 apiEndpoint 變數設定為已部署 API 的 URL (http://<app_name>.azurewebsites.net)。In Line 51, set the apiEndpoint variable to the URL of your deployed API (http://<app_name>.azurewebsites.net). 以您在 App Service 中的應用程式名稱取代 <appname>Replace <appname> with your app name in App Service.

在您的本機終端機視窗中,再次執行範例應用程式。In your local terminal window, run the sample app again.

dotnet run

瀏覽至位於 http://localhost:5000 的瀏覽器應用程式。Navigate to the browser app at http://localhost:5000. 在瀏覽器中開啟 [開發人員工具] 視窗 (在適用於 Windows 的 Chrome 中按 Ctrl+Shift+i),並檢查 [主控台] 索引標籤。您現在會看到錯誤訊息:No 'Access-Control-Allow-Origin' header is present on the requested resourceOpen the developer tools window in your browser (Ctrl+Shift+i in Chrome for Windows) and inspect the Console tab. You should now see the error message, No 'Access-Control-Allow-Origin' header is present on the requested resource.

瀏覽器用戶端中的 CORS 錯誤

因為瀏覽器應用程式 (http://localhost:5000) 與遠端資源 (http://<app_name>.azurewebsites.net) 之間的網域不相符,加上 App Service 中您的 API 並未傳送 Access-Control-Allow-Origin 標頭的這個事實,以致瀏覽器無法將跨網域內容載入瀏覽器應用程式中。Because of the domain mismatch between the browser app (http://localhost:5000) and remote resource (http://<app_name>.azurewebsites.net), and the fact that your API in App Service is not sending the Access-Control-Allow-Origin header, your browser has prevented cross-domain content from loading in your browser app.

在生產環境中,瀏覽器應用程式會有公用 URL (而非 localhost URL),但是對 localhost URL 啟用 CORS 的方式與公用 URL 相同。In production, your browser app would have a public URL instead of the localhost URL, but the way to enable CORS to a localhost URL is the same as a public URL.

啟用 CORSEnable CORS

在 Cloud Shell 中,使用 az resource update 命令,對您的用戶端 URL 啟用 CORS。In the Cloud Shell, enable CORS to your client's URL by using the az resource update command. 取代 <appname> 預留位置。Replace the <appname> placeholder.

az resource update --name web --resource-group myResourceGroup --namespace Microsoft.Web --resource-type config --parent sites/<app_name> --set properties.cors.allowedOrigins="['http://localhost:5000']" --api-version 2015-06-01

您可以在 properties.cors.allowedOrigins ("['URL1','URL2',...]") 中設定多個用戶端 URL。You can set more than one client URL in properties.cors.allowedOrigins ("['URL1','URL2',...]"). 您也可以使用 "['*']" 來啟用所有的用戶端 URL。You can also enable all client URLs with "['*']".


如果您的應用程式需要傳送認證,例如 Cookie 或驗證權杖,則瀏覽器可能會在回應上要求 ACCESS-CONTROL-ALLOW-CREDENTIALS 標頭。If your app requires credentials such as cookies or authentication tokens to be sent, the browser may require the ACCESS-CONTROL-ALLOW-CREDENTIALS header on the response. 若要在 App Service 中啟用此作業,請在 CORS 組態中將 properties.cors.supportCredentials 設定為 true。當 allowedOrigins 包含 '*' 時,無法啟用此作業。To enable this in App Service, set properties.cors.supportCredentials to true in your CORS config. This cannot be enabled when allowedOrigins includes '*'.

再次測試 CORSTest CORS again

重新整理位於 http://localhost:5000 的瀏覽器應用程式。Refresh the browser app at http://localhost:5000. [主控台] 視窗中的錯誤訊息現已消失,而且您可看到來自已部署 API 的資料並與其互動。The error message in the Console window is now gone, and you can see the data from the deployed API and interact with it. 您的遠端 API 現在對在本機執行的瀏覽器應用程式支援 CORS。Your remote API now supports CORS to your browser app running locally.

瀏覽器用戶端中的 CORS 成功

恭喜,您正在 Azure App Service 中執行具有 CORS 支援的 API。Congratulations, you're running an API in Azure App Service with CORS support.

App Service CORS 與您的 CORSApp Service CORS vs. your CORS

您可使用自己的 CORS 公用程式,而不是使用 App Service CORS,以獲得更大彈性。You can use your own CORS utilities instead of App Service CORS for more flexibility. 例如,您可以針對不同的路由或方法,指定不同的允許來源。For example, you may want to specify different allowed origins for different routes or methods. 因為 App Service CORS 可讓您針對所有的 API 路由和方法指定一組可接受的來源,所以您可使用自己的 CORS 程式碼。Since App Service CORS lets you specify one set of accepted origins for all API routes and methods, you would want to use your own CORS code. 啟用跨源要求 (CORS)中了解 ASP.NET Core 如何執行此作業。See how ASP.NET Core does it at Enabling Cross-Origin Requests (CORS).


請勿嘗試同時使用 App Service CORS 與您自己的 CORS 程式碼。Don't try to use App Service CORS and your own CORS code together. 一起使用時,App Service CORS 具有優先權,而您自己的 CORS 程式碼沒有任何作用。When used together, App Service CORS takes precedence and your own CORS code has no effect.

清除資源Clean up resources

在前述步驟中,您在資源群組中建立了 Azure 資源。In the preceding steps, you created Azure resources in a resource group. 如果您在未來不需要這些資源,請在 Cloud Shell 中執行下列命令,刪除資源群組:If you don't expect to need these resources in the future, delete the resource group by running the following command in the Cloud Shell:

az group delete --name myResourceGroup

此命令可能會花一分鐘執行。This command may take a minute to run.

後續步驟Next steps

您已了解如何︰What you learned:

  • 使用 Azure CLI 建立 App Service 資源Create App Service resources using Azure CLI
  • 使用 Git 將 RESTful API 部署到 AzureDeploy a RESTful API to Azure using Git
  • 啟用 App Service CORS 支援Enable App Service CORS support

移至下一個教學課程,以了解如何為使用者進行驗證和授權。Advance to the next tutorial to learn how to authenticate and authorize users.