Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

Tutorial: Deploy an ASP.NET app with Azure SQL database to Azure

  • 2025-06-26
Feedback

In this article

Azure App Service provides a highly scalable, self-patching web hosting service. This tutorial shows you how to deploy a data-driven ASP.NET app in App Service and connect it toAzure SQL Database.

When you finish the tutorial, you have an ASP.NET app connected to an Azure SQL database running in Azure. The following example shows the app interface.

Screenshot that shows a published ASP.NET application in Azure App Service.

In this tutorial, you:

  • Publish a data-driven web app to Azure.
  • Create an Azure SQL database to hold the app data.
  • Connect the ASP.NET app to the Azure SQL database.
  • Configure a managed identity and Microsoft Entra ID authentication for the database connection.
  • Update the data model and redeploy the app.
  • Stream application logs from Azure to Visual Studio.

Prerequisites

  • If you don't have an Azure account, create afree account before you begin.
  • InstallVisual Studio 2022 with theASP.NET and web development andAzure development workloads.
    • You can add the workloads to an existing Visual Studio installation by selectingGet Tools and Features in the Visual StudioTools menu.
    • Make sure you have the latest updates for Visual Studio 2022 by selectingHelp >Check for updates and installing the latest version if necessary.

Create and run the app

The sample project contains a basicASP.NET MVC create-read-update-delete (CRUD) app that usesEntity Framework Code First.

  1. Download thesample project and extract thedotnet-sqldb-tutorial-master.zip file.

  2. Open the extracteddotnet-sqldb-tutorial-master/DotNetAppSqlDb.sln file in Visual Studio.

  3. PressF5 to run the app and open it in your default browser.

  4. In the app, selectCreate New and create a couple ofto-do items.

    Screenshot that shows the ASP.NET web app.

  5. Test theEdit,Details, andDelete links.

Publish the app to Azure

To publish the app to Azure, you create and configure a Publish profile that has an Azure App Service and App Service Plan to host the app. You then create an Azure SQL Server and Azure SQL database to contain the app data, and configure a database context to connect the app with the database.

  1. In Visual StudioSolution Explorer, right-click theDotNetAppSqlDb project and selectPublish.

    Screenshot that shows Publish from Solution Explorer.

  2. On thePublish screen, selectAzure as your target and selectNext.

  3. On the next screen, make sure thatAzure App Service (Windows) is selected and selectNext.

Sign in and add an Azure App Service

  1. On the nextPublish screen, sign in to your Microsoft account and the subscription you want to use.

  2. Next toApp Service, selectCreate new.

    Screenshot that shows selecting Create new for App Service in the Publish pane.

Configure the Azure App Service

  1. On theApp Service (Windows) screen, configure the App ServiceName,Resource group, andHosting Plan.

    Screenshot that shows creating an App Service plan.

  2. UnderName, you can keep the generated web app name, or change it to another name with charactersa-z,0-9, and-. The web app name must be unique across all Azure apps.

  3. Next toResource group, selectNew, and name the resource groupmyResourceGroup.

    Aresource group is a logical container into which Azure resources, such as 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.

  4. Next toHosting Plan, selectNew.

    AnApp Service plan specifies the location, size, and features of the web server farm that hosts your app. You can save money when you host multiple apps by configuring the web apps to share a single App Service plan.

    App Service plans define:

    • Region (for example: North Europe, East US, or Southeast Asia)
    • Instance size (small, medium, or large)
    • Scale count (1 to 20 instances)
    • SKU (Free, Shared, Basic, Standard, or Premium)
  5. Complete theHosting Plan screen, and then selectOK.

    SettingSuggested valueFor more information
    App Service PlanmyAppServicePlanApp Service plans
    LocationEast USAzure regions
    SizeFreePricing tiers

    Screenshot that shows creating the Hosting Plan.

  6. On theApp Service (Windows) screen, selectCreate, and wait for the Azure resources to be created.

  7. ThePublish screen shows the resources you configured. SelectFinish, and then selectClose.

    Screenshot that shows the resources you created.

Create a server and database

Before you can create a database, you need alogical SQL server. A logical SQL server is a logical construct that contains a group of databases managed as a group.

  1. On thePublish screen for theDotNetAppSqlDb app, in theService Dependencies section, select the ellipsis... next toSQL Server Database, and selectConnect.

    Note

    Be sure to configure the SQL Database from thePublish tab, not theConnected Services tab.

    Screenshot that shows configuring the SQL Database dependency.

  2. On theConnect to dependency screen, selectAzure SQL Database and then selectNext.

  3. On theConfigure Azure SQL Database screen, selectCreate new.

  4. On theAzure SQL Database screen, next toDatabase server, selectNew.

  5. Change the server name to a value you want. The server name must be unique across all servers in Azure SQL.

  6. SelectOK.

    Screenshot that shows creating the server.

  7. On theAzure SQL Database screen, keep the default generatedDatabase Name. SelectCreate and wait for the database resources to be created.

    Screenshot that shows configuring the database.

  8. When the database resources are created, selectNext.

  9. On theConnect to Azure SQL Database screen, selectFinish.

    Screenshot of the screen with messagea about configuring managed identity for the connection to work.

    Note

    If you seeLocal user secrets files instead, make sure you used thePublish page, not theConnected Services page, to configure SQL Database.

Your Azure SQL Database connection is now set up to use Managed Identity for Azure services, a secure method of connecting your app to your Azure resources that doesn't use secrets or passwords. You now need to set the appropriate permissions on the SQL user corresponding with this managed identity for the connection to work.

Configure managed identity

When the Azure SQL Database creation wizard set up the Azure SQL server with a managed identity and Entra ID Default authentication, it added your Entra ID account as the Azure SQL admin. If you're signed in to the same account in Visual Studio, you can use the same connection string to connect to the database in both Visual Studio and Azure.

  1. From theTools menu, selectNuGet Package Manager >Package Manager Console.

  2. In thePackage Manager Console, install the following packages:

    Install-Package Microsoft.Data.SqlClientInstall-Package Microsoft.EntityFramework.SqlServer
  3. In a PowerShell command line, run the following command to sign in to SQL Database, replacing<server-name> with your server name and<entra-id-user> with the Microsoft Entra user name you used to set up the database in Visual Studio. That Entra user has admin access to the database server by default.

    sqlcmd -S <servername>.database.windows.net -d DotNetAppSqlDb_db -U <entra-id-user> -G -l 30

    Follow the prompts to sign in.

  4. At the SQL prompt, run the following commands to grant the minimum permissions your app needs, replacing<app-name> with your app name.

    CREATE USER [<app-name>] FROM EXTERNAL PROVIDER;ALTER ROLE db_datareader ADD MEMBER [<app-name>];ALTER ROLE db_datawriter ADD MEMBER [<app-name>];ALTER ROLE db_ddladmin ADD MEMBER [<app-name>];GO

Update the database context

The app uses a database context to connect with the database, which is referenced in theModels/MyDatabaseContext.cs file. In this section, you update the code to refer to the Entity Framework 6 SQL Server provider, which depends on the modernMicrosoft.Data.SqlClient ADO.NET provider.

The Entity Framework 6 provider replaces the built-inSystem.Data.SqlClient SQL Server provider, and includes support for Microsoft Entra ID authentication methods. For more information, seeMicrosoft.EntityFramework.SqlServer}.

[DbConfigurationType(typeof(MicrosoftSqlDbConfiguration))] works locally to useMicrosoft.Data.SqlClient for the database context, but becauseSystem.Data.SqlClient is hardcoded as the provider in Azure App Service, you need to extendMicrosoftSqlDbConfiguration to redirect references toSystem.Data.SqlClient toMicrosoft.Data.SqlClient instead.

  1. Inweb.config, remove theentityFramework/providers/provider section and line:<provider invariantName="System.Data.SqlClient" .../>.

  2. InModels/MyDatabaseContext.cs, add the following class:

        public class AppServiceConfiguration : MicrosoftSqlDbConfiguration    {        public AppServiceConfiguration()        {            SetProviderFactory("System.Data.SqlClient", Microsoft.Data.SqlClient.SqlClientFactory.Instance);            SetProviderServices("System.Data.SqlClient", MicrosoftSqlProviderServices.Instance);            SetExecutionStrategy("System.Data.SqlClient", () => new MicrosoftSqlAzureExecutionStrategy());        }    }
  3. Add the following attribute to theMyDatabaseContext class declaration:

    [DbConfigurationType(typeof(AppServiceConfiguration))]

Deploy the ASP.NET app

  1. At the top of thePublish tab, selectPublish. Your ASP.NET app deploys to Azure, and your default browser launches to the URL of the deployed app.

  2. To test the app, add a few to-do items.

    Screenshot that shows the published ASP.NET application in Azure App Service.

Congratulations! Your data-driven ASP.NET application is running live in Azure App Service.

Use SQL Server Object Explorer

You can use Visual StudioSQL Server Object Explorer to easily explore and manage your Azure SQL database. InSQL Server Object Explorer, you can perform most common database operations, such as running queries or creating tables, views, and stored procedures.

Allow client connection from your computer

By default, the Azure server allows connections to its databases only from Azure services, such as your Azure app. The new database opened its firewall to the App Service app you created.

To access the database from your local computer, such as from Visual Studio, the Azure server must open the firewall to allow access for the machine's public IP address.

If prompted to add access for your local client, make sure to select the option toAllow your computer's public IP address. This option creates a firewall rule to allow the public IP address of your local computer. The dialog box is already populated with your computer's current IP address.

If you don't get a prompt to add access for your local computer, you can go to your Azure SQL database in the Azure portal and selectSet server firewall on the top menu bar. On theNetworking page underFirewall rules, select the option toAdd your client IPv4 address.

Note

If your internet service provider changes your public IP address, you need to reconfigure the firewall to access the Azure database again.

Connect to the Azure SQL database locally

  1. From theView menu, selectSQL Server Object Explorer.

  2. At the top of theSQL Server Object Explorer window, select the icon toAdd SQL Server.

  3. On theConnect screen, your connection appears under theAzure node. Complete the information for yourServer Name,User Name,Password, andDatabase Name, and selectConnect.

    Screenshot that shows configuring the database connection from Visual Studio.

  4. Once Visual Studio finishes configuring the connection for your SQL Database instance, your database appears inSQL Server Object Explorer. Expand<your connection name> >Databases ><your database name> > to see the data.

  5. ExpandTables, right-click theToDoes table, and selectView Data to interact with the database data.

    Screenshot that shows exploring SQL Database objects.

Update the app with Code First Migrations

You can use familiar tools in Visual Studio to update your database and app in Azure. In this step, you use Code First Migrations in Entity Framework to change your database schema and publish the change to Azure.

For more information about using Entity Framework Code First Migrations, seeGetting Started with Entity Framework 6 Code First using MVC 5.

Update your data model

OpenModels\Todo.cs in the code editor. Add the following property to theToDo class:

public bool Done { get; set; }

Run Code First Migrations locally

Run a few commands to make updates to your local database.

  1. From theTools menu, selectNuGet Package Manager >Package Manager Console.

  2. In the Package Manager Console window, enable Code First Migrations:

    Enable-Migrations
  3. Add a migration:

    Add-Migration AddProperty
  4. Update the local database:

    Update-Database
  5. PressCtrl+F5 to run the app. Test theEdit,Details, andCreate New links.

If the application loads without errors, Code First Migrations succeeded. However, your page still looks the same because your application logic isn't using this new property yet.

Use the new property

Make some changes in your code to see theDone property in action. For this tutorial, you change only theIndex andCreate views to use the new property.

  1. OpenControllers\TodosController.cs, and in theCreate() method on line 52, addDone to the list of properties in theBind attribute. YourCreate() method signature should look like the following code:

    public ActionResult Create([Bind(Include = "Description,CreatedDate,Done")] Todo todo)
  2. OpenViews\Todos\Create.cshtml, and in the Razor code, note the<div> element that usesmodel.Description and the<div> element that usesmodel.CreatedDate.

    After these two elements, add the following<div> element that usesmodel.Done:

    <div>    @Html.LabelFor(model => model.Done, htmlAttributes: new { @class = "control-label col-md-2" })    <div>        <div>            @Html.EditorFor(model => model.Done)            @Html.ValidationMessageFor(model => model.Done, "", new { @class = "text-danger" })        </div>    </div></div>
  3. OpenViews\Todos\Index.cshtml, and just above the empty<th></th> element, add the following Razor code:

    <th>    @Html.DisplayNameFor(model => model.Done)</th>
  4. Above the<td> element that contains theHtml.ActionLink() helper methods, add another<td> element with the following Razor code:

    <td>    @Html.DisplayFor(modelItem => item.Done)</td>
  5. Save all files, and pressCtrl+F5 to run the app.

  6. In the app, add a to-do item and selectDone. The item should appear on your home page as a completed item. TheEdit view doesn't show theDone field, because you didn't change theEdit view.

Enable Code First Migrations in Azure

Now that your code change works, including database migration, you can publish it to your Azure app and update your Azure SQL database with Code First Migrations too.

  1. In Visual StudioSolution Explorer, right-click your project and selectPublish.

  2. SelectMore actions >Edit to open the publish settings.

    Screenshot that shows opening publish settings.

  3. In theMyDatabaseContext dropdown, select the database connection for your Azure SQL database.

  4. SelectExecute Code First Migrations (runs on application start), and then selectSave.

    Screenshot that shows Enable Code First Migrations in Azure app.

Publish your changes

Now that you enabled Code First Migrations in your Azure app, publish your code changes.

  1. On thePublish page, selectPublish.

  2. In the published web app, try adding more to-do items again and selectingDone, and they should appear on your home page as completed items.

    All your existing to-do items are still displayed. When you republish your ASP.NET application, existing data in your Azure SQL database isn't lost. Also, Code First Migrations only changes the data schema and leaves your data intact.

    Screenshot that shows the Azure app after Code First Migration.

Stream application logs

You can stream tracing messages directly from your Azure app to Visual Studio.

OpenControllers\TodosController.cs, and note that each action starts with aTrace.WriteLine() method. This code shows you how to add trace messages to your Azure app.

Enable log streaming

  1. On the Visual StudioPublish page, scroll down to theHosting section.

  2. Select the ellipsis... at upper right and selectView streaming logs.

    Screenshot that shows Enable log streaming.

    The logs are now streamed into theOutput window.

    Screenshot that shows Log streaming in the Output window.

    You don't see any trace messages yet, because when you first selectView streaming logs, your Azure app sets the trace level toError, which logs only error events using theTrace.TraceError() method.

Change trace levels

  1. To change the trace levels to output other trace messages, in theHosting section of thePublish page, select the... at upper right and then selectOpen in Azure portal.

  2. On the Azure portal page for your app, selectApp Service logs underMonitoring in the left menu.

  3. UnderApplication logging (Filesystem), selectVerbose underLevel, and then selectSave.

    Tip

    You can experiment with different trace levels to see what types of messages are displayed for each level. For example, theInformation level includes all logs created byTrace.TraceInformation(),Trace.TraceWarning(), andTrace.TraceError(), but not logs created byTrace.WriteLine().

  4. In your browser, go to your Azure to-do list application again and navigate around the app. Trace messages like the following examples now stream to theOutput window in Visual Studio.

    Application:2025-05-12T23:41:11  PID[17108] Verbose     GET /Todos/IndexApplication:2025-05-12T23:42:04  PID[17108] Verbose     GET /Todos/IndexApplication:2025-05-12T23:42:06  PID[17108] Verbose     POST /Todos/CreateApplication:2025-05-12T23:42:07  PID[17108] Verbose     GET /Todos/Index

Stop log streaming

To stop the log-streaming service, select theStop monitoring icon in theOutput window.

Screenshot that shows Stop log streaming.

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, you can delete them by deleting the resource group.

  1. From your web app'sOverview page in the Azure portal, select themyResourceGroup link underResource group.
  2. On the resource group page, make sure that the listed resources are the ones you want to delete.
  3. SelectDelete resource group, typemyResourceGroup in the text box, and then selectDelete.
  4. Confirm again by selectingDelete.

Related content

Go to the next tutorial to learn how to use managed identity to improve Azure SQL Database connection security.


Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo