RESTful API with CORS in Azure App Service

Tutorial: Host a RESTful API with CORS in Azure App Service

  • 02/28/2018
  • 8 minutes to read
  • Contributors

In this article

Azure App Service provides a highly scalable, self-patching web hosting service. In addition, App Service has built-in support for Cross-Origin Resource Sharing (CORS) for RESTful APIs. This tutorial shows how to deploy an ASP.NET Core API app to App Service with CORS support. You configure the app using command-line tools and deploy the app using Git.

In this tutorial, you learn how to:

  • Create App Service resources using Azure CLI
  • Deploy a RESTful API to Azure using Git
  • Enable App Service CORS support

You can follow the steps in this tutorial on macOS, Linux, Windows.

If you don’t have an Azure subscription, create a free account before you begin.

Prerequisites

To complete this tutorial:

Create local ASP.NET Core app

In this step, you set up the local ASP.NET Core project. App Service supports the same workflow for APIs written in other languages.

Clone the sample application

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

This repository contains an app that’s created based on the following tutorial: ASP.NET Core Web API help pages using Swagger. 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

Navigate to http://localhost:5000/swagger in a browser to play with the Swagger UI.

Navigate to http://localhost:5000/api/todo and see a list of ToDo JSON items.

Navigate to http://localhost:5000 and play with the browser app. Later, you will point the browser app to a remote API in App Service to test CORS functionality. Code for the browser app is found in the repository’s wwwroot directory.

To stop ASP.NET Core at any time, press Ctrl+C in the terminal.

Launch Azure Cloud Shell

The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common Azure tools preinstalled and configured to use with your account. Just click the Copy button to copy the code, paste it into the Cloud Shell, and then press enter to run it. There are a few ways to launch the Cloud Shell:

Click Try It in the upper right corner of a code block.
Open Cloud Shell in your browser.
Click the Cloud Shell button on the menu in the upper right of the Azure portal.

Deploy app to Azure

In this step, you deploy your SQL Database-connected .NET Core application to App Service.

Configure local git deployment

In the Cloud Shell, create deployment credentials with the az webapp deployment user set command. This deployment user is required for FTP and local Git deployment to a web app. The user name and password are account level. They are different from your Azure subscription credentials.

In the following example, replace <username> and <password> (including brackets) with a new user name and password. The user name must be unique within Azure. The password must be at least eight characters long, with two of the following three elements: letters, numbers, symbols.

az webapp deployment user set --user-name <username> --password <password>

You should get a JSON output, with the password shown as null. If you get a 'Conflict'. Details: 409 error, change the username. If you get a 'Bad Request'. Details: 400 error, use a stronger password.

You create this deployment user only once; you can use it for all your Azure deployments.

Note

Record the user name and password. You need them to deploy the web app later.

Create a resource group

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.

In the Cloud Shell, create a resource group with the az group create command. The following example creates a resource group named myResourceGroup in the West Europe location. 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.

When the command finishes, a JSON output shows you the resource group properties.

Create an App Service plan

In the Cloud Shell, create an App Service plan with the az appservice plan create command.

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

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
} 

Create a web app

Create a web app in the myAppServicePlan App Service plan.

In the Cloud Shell, you can use the az webapp create command. 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

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. >
}

You’ve created an empty web app in a Linux container, with git deployment enabled.

Note

The URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://<username>@<app_name>.scm.azurewebsites.net/<app_name>.git. Save this URL as you need it later.

Push to Azure from Git

Back in the local terminal window, add an Azure remote to your local Git repository. 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>

Push to the Azure remote to deploy your app with the following command. 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 log 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

Browse to the Azure web app

Navigate to http://<app_name>.azurewebsites.net/swagger in a browser and play with the Swagger UI.

Navigate to http://<app_name>.azurewebsites.net/swagger/v1/swagger.json to see the swagger.json for your deployed API.

Navigate to http://<app_name>.azurewebsites.net/api/todo to see your deployed API working.

Add CORS functionality

Next, you enable the built-in CORS support in App Service for your API.

Test CORS in sample app

In your local repository, open wwwroot/index.html.

In Line 51, set the apiEndpoint variable to the URL of your deployed API (http://<app_name>.azurewebsites.net). Replace <appname> with your app name in App Service.

In your local terminal window, run the sample app again.

dotnet run

Navigate to the browser app at http://localhost:5000. Open 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.

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.

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.

Enable CORS

In the Cloud Shell, enable CORS to your client’s URL by using the az resource update command. 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

You can set more than one client URL in properties.cors.allowedOrigins ("['URL1','URL2',...]"). You can also enable all client URLs with "['*']".

Test CORS again

Refresh the browser app at http://localhost:5000. The error message in the Console window is now gone, and you can see the data from the deployed API and interact with it. Your remote API now supports CORS to your browser app running locally.

Congratulations, you’re running an API in Azure App Service with CORS support.

App Service CORS vs. your 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. 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. See how ASP.NET Core does it at Enabling Cross-Origin Requests (CORS).

Note

Don’t try to use App Service CORS and your own CORS code together. When used together, App Service CORS takes precedence and your own CORS code has no effect.

Clean up resources

In the preceding steps, you created Azure resources in a resource group. 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:

  • Create App Service resources using Azure CLI
  • Deploy a RESTful API to Azure using Git
  • Enable App Service CORS support

Advance to the next tutorial to learn how to authenticate and authorize users.

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

This site uses Akismet to reduce spam. Learn how your comment data is processed.

TOP