Getting Started with API apps, ASP. NET, and Swagger in Azure app service

Source: Internet
Author: User
Tags app service response code unique id server memory azure sdk

Learning content:

    • How to create and deploy API apps in Azure app service with built-in tools in Visual Studio 2015.
    • How to use the Swashbuckle NuGet package to dynamically generate Swagger API metadata for automated API discovery.
    • How to use the Swagger API metadata to automatically generate client code for an API app.
Note

To connect Visual Studio to the Azure China region, you can follow the instructions in Azure, which connects to the China region using Visual Studio 2015.

If you are using Visual Studio Update 2 or later, you can select the Enable isolated Azure Active Directory configuration option by following the instructions in the slice.

If you are using Visual Studio 2017, you can follow the instructions in using Visual Studio 2017 to connect to the Chinese region of Azure.

Sample Application Overview

This tutorial uses a simple to-do column to represent the sample application. The application includes a single-page application (SPA) frontend, ASP. NET Web API middle tier, and ASP. NET Web API data tier.

The following is the AngularJS front-end screen.

The Visual Studio solution consists of three projects:

    • todolistangular -front end: AngularJS SPA for calling the middle tier.

    • Todolistapi -middle tier: calls the data layer and treats the ASP. NET Web API project that performs CRUD operations.

    • TODOLISTDATAAPI -Data layer: an ASP. NET Web API project that treats the CRUD operations of a business.

A three-tier architecture is one of several architectures that can be implemented using API apps, which are used only for demonstration purposes. The code in each layer is as simple as possible to demonstrate API application functionality; For example, the data tier uses server memory instead of a database as a persistence mechanism.

After completing this tutorial, you will create two Web API projects that are launched and run in the app service API app in the cloud.

The next article in this series of tutorials deploys the SPA front-end to the cloud.

Prerequisite
    • ASP.-The instructions in this tutorial assume that the reader has a basic understanding of how to use ASP. NET Web API 2 in Visual Studio.

    • Azure Account-You can open an Azure account.

    • Visual Studio 2015 and Azure sdk-sdk for. NET automatically install Visual Studio 2015 if it is not already installed.

      • In Visual Studio, click Help, about Microsoft Visual Studio, and make sure that Azure App Service Tools v2.9.1 or later is installed.

        Note

        Depending on the number of SDK dependencies that are already on your computer, installing the SDK can take a long time, ranging from a few minutes to half an hour or longer.

Download the sample application
    1. Download the Azure-samples/app-service-api-dotnet-to-do-list repository.

      You can click the Download ZIP button, or clone the repository on your local computer.

    2. Open the ToDoList solution in Visual Studio 2015 or 2013.

      1. Each solution needs to be trusted.
    3. Build the solution (CTRL + SHIFT + B) to restore the NuGet package.

      If you want to see how your application is running before you deploy it, you can run the application locally. Make sure that TODOLISTDATAAPI is the startup project, and then run the solution. The HTTP 403 error should be seen in the browser.

Using the Swagger API metadata and UI

Azure app service built-in Swagger 2.0 API metadata support. Each API app can specify a URL endpoint that returns API metadata in Swagger JSON format. The metadata returned from this endpoint can be used to generate client code.

The ASP. NET Web API Project can dynamically generate Swagger metadata using the Swashbuckle NuGet package. The Swashbuckle NuGet package is installed in the downloaded TODOLISTDATAAPI and TODOLISTAPI projects.

Review the generated Swagger 2.0 metadata in this section of the tutorial, and then try to use the test UI based on the Swagger metadata.

  1. Set the TODOLISTDATAAPI project ( not the TODOLISTAPI project) as the startup project.

  2. Press F5 or click Debug > Start Debugging to run the project in debug mode.

    The browser opens and displays the HTTP 403 errors page.

  3. In the address bar of the browser, add at the end of the URL line and swagger/docs/v1 press ENTER. (URL is http://localhost:45914/swagger/docs/v1 . )

    This is the default URL for the Swagger 2.0 JSON metadata that Swashbuckle is used to return the API.

    If you are using Internet Explorer, the browser prompts you to download the v1.json file.

    If you are using Chrome, Firefox, or Edge, the browser displays JSON in the browser window. Different browsers have different JSON processing methods, so the browser window may not look exactly the same as the example.

    The following example shows the first part of the API's Swagger metadata, which contains the definition of the Get method. The Swagger UI used in the following steps is driven by this metadata, which is used later in this tutorial to automatically generate client code.

    Copy
    {  "swagger": "2.0",  "info": {    "version": "v1",    "title": "ToDoListDataAPI"  },  "host": "localhost:45914",  "schemes": [ "http" ],  "paths": {    "/api/ToDoList": {      "get": {        "tags": [ "ToDoList" ],        "operationId": "ToDoList_GetByOwner",        "consumes": [ ],        "produces": [ "application/json", "text/json", "application/xml", "text/xml" ],        "parameters": [          {            "name": "owner",            "in": "query",            "required": true,            "type": "string"          }        ],        "responses": {          "200": {            "description": "OK",            "schema": {              "type": "array",              "items": { "$ref": "#/definitions/ToDoItem" }            }          }        },        "deprecated": false      },
  4. Close the browser and stop Visual Studio debugging.

  5. Open the app_start\swaggerconfig.cs file in the TODOLISTDATAAPI project in Solution Explorer, and then scroll down to line 174th and uncomment the following code.

    Copy
    /*    }).EnableSwaggerUi(c =>    {*/

    The SwaggerConfig.cs file is created when you install the Swashbuckle package in your project. This file provides several ways to configure Swashbuckle.

    The code that has been uncomment will enable the Swagger UI to be used in the following steps. As a security measure, this code is commented by default when you create a WEB API project using the API App project template.

  6. Run the project again.

  7. In the address bar of the browser, add at the end of the URL line and swagger press ENTER. (URL is http://localhost:45914/swagger . )

  8. When the Swagger UI page appears, click ToDoList to view the available methods.

  9. Click the first "Get" button in the list.

  10. In the Parameters section, enter an asterisk as owner the value for the parameter, and then click Try.

    When you add authentication in subsequent tutorials, the middle tier provides the actual user ID for the data tier. Now, when the application runs without authentication enabled, all tasks are marked with an asterisk as their owner ID.

    The Swagger UI calls the ToDoList Get method and displays the response code and JSON results.

  11. Click Post, and then click the box under model schema.

    Clicking the model schema will pre-populate the input box, where you can specify the parameter values for the Post method. (If this does not apply to Internet Explorer, use a different browser or manually enter the parameter values in the next step.) )

  12. Change the JSON in the todo parameter input box, or replace it with your own description text, as shown in the following example:

    Copy
    {  "ID": 2,  "Description": "buy the dog a toy",  "Owner": "*"}
  13. Click "Try".

    The ToDoList API returns an HTTP 204 response code that represents a success.

  14. Click the First Get button, and then click the Try button in that section of the page.

    The Get method response now contains a new to-dos item.

  15. Optional: You can also try using the Put, Delete, and Get by ID methods.

  16. Close the browser and stop Visual Studio debugging.

Swashbuckle can be used for any ASP. NET Web API project. If you want to add Swagger metadata generation to an existing project, simply install the Swashbuckle package.

Note

The Swagger metadata contains a unique ID for each API operation. By default, Swashbuckle may generate duplicate Swagger operation IDs for Web API controller methods. This can happen if the controller has overloaded HTTP methods (for example Get() Get(id) , and). For information about how to handle overloading, see Customizing Swashbuckle generated API definitions. If you create a WEB API project using the Azure API application template in Visual Studio, the code that generates a unique action ID is automatically added to theSwaggerConfig.cs file.

Create an API app in Azure and deploy code to it

This section uses the Azure tools that are integrated into the Publish Web Wizard in Visual Studio to create a new API app in Azure. Then, deploy the TODOLISTDATAAPI project to the new API app and invoke the API by running the Swagger UI.

  1. In Solution Explorer, right-click the Todolistdataapi project, and then click Publish.

  2. In the Publish Web Wizard, in the configuration file step, click Azure App Service.

  3. If you are not already signed in, sign in to your Azure account, or refresh your credentials if your credentials have expired.

  4. In the App Service dialog box, select the Azure subscription you want to use, and then click Add.

    The Managed tab of the Create App Service dialog box appears.

    Because you are deploying a WEB API project that has Swashbuckle installed, Visual Studio assumes that you want to create an API app. This is indicated by the API app name title, which is also seen in the "Change Type" drop-down list, which is set to "API app".

  5. Enter the name of the API app that is unique in the chinacloudsites.cn domain. You can accept the default name recommended by Visual Studio.

    If you enter a name that is already in use, a red exclamation mark appears on the right.

    The URL for the API app is {API app name}.chinacloudsites.cn .

  6. In the Resource group drop-down list, click New, and then enter a name for Todolistgroup or other preferences.

    A resource group is a collection of Azure resources, such as API apps, databases, VMS, and so on. In this tutorial, it's a good idea to create a new resource group because it's easy to remove all of the Azure resources created for this tutorial in one step.

    Use this box to select an existing resource group, or to create a new resource group by typing a different name from any existing resource group in the subscription.

  7. Click the New button next to the app service plan drop-down list.

    The screen shows sample values for the API app name, subscription, and resource group-the value of the user will vary.

    The following steps create an app service plan for a new resource group. The App service plan specifies the compute resources where the API app runs. For example, if you choose a free tier, the API application will run on a shared VM, and if you select some paid tier, it runs on a dedicated VM. For information about app service plans, see app Service plans overview.

  8. In the Configure App Service Plan dialog box, enter a name for "Todolistplan" or another preference.

  9. In the Location drop-down list, select the location that is closest to you.

    This setting specifies which Azure data center your app will run in. Select the closest location to minimize the delay.

  10. In the Size drop-down list, click Free.

    For this tutorial, the free pricing tier provides enough performance.

  11. In the Configure App Service Plan dialog box, click OK.

  12. In the Create App Service dialog box, click Create.

    Visual Studio creates an API app and a publishing profile that contains all the required settings for the API app. Then, you open the Publish Web Wizard to deploy the project.

    The Publish Web Wizard that opens initially displays the Connections tab (shown below).

    On the Connections tab, the server and site name settings point to the API app. The user name and password are the deployment credentials created by Azure. After deployment, Visual Studio opens the destination URLin the browser (this is the only purpose of the destination URL ).

  13. Click Next.

    The next tab is the Settings tab (shown below). You can change the build Configuration tab here to deploy a debug build for remote debugging. This tab also provides multiple file publishing options:

    • Delete other files at the target
    • precompiled during publishing
    • Exclude files from the App_Data folder

    In this tutorial, you do not need to use these options. For an explanation of the effects of these options, see how To:deploy a Web Project using One-click Publish in Visual Studio: Deploying a Web with one-click Publishing in Visual Studio Project).

  14. Click Next.

    Next is the Preview tab, shown below, to see which files are about to be copied from the project to the API app. If you are deploying your project to an API app that you have previously deployed to, only the files that have changed will be copied. If you want to see a list of items to copy, click the Start Preview button.

  15. Click Publish.

    Visual Studio deploys the TODOLISTDATAAPI project to the new API app. The Output window records a successful deployment, and the successfully created page appears in the browser window with the API app URL open.

  16. In the address bar of the browser, add "swagger" to the URL, and then press Enter. (URL is http://{apiappname}.chinacloudsites.cn/swagger . )

    The browser will display the same Swagger UI that appears earlier, but the UI is now running in the cloud. If you try to use the Get method, you will find that you have returned to the default 2 todo items. The changes that you made earlier have been saved in memory on the local computer.

  17. Open the Azure portal.

    The Azure portal is a WEB interface for managing Azure resources, such as API apps.

  18. Click More Services > Application services.

  19. In the application services blade, locate and click the new API app. (In the Azure Portal, the window that opens on the right is called a blade .) )

    Two blades will open. One of the blades contains an overview of the API app, and the other contains a long list of settings that you can view and change.

  20. In the settings blade, locate the API section and click API Definitions.

    Use the API definition blade to specify a URL that returns Swagger 2.0 metadata in JSON format. When Visual Studio creates an API app, the API definition URL is set to the metadata default value generated by the swashbuckle shown earlier, which is the base URL of the API app plus /swagger/docs/v1 .

    When you select the API app for which you want to generate client code, Visual Studio retrieves the metadata from this URL.

More study Materials

Getting Started with API apps, ASP. NET, and Swagger in Azure app service

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.