This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
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.
In this tutorial, you:
The sample project contains a basicASP.NET MVC create-read-update-delete (CRUD) app that usesEntity Framework Code First.
Download thesample project and extract thedotnet-sqldb-tutorial-master.zip file.
Open the extracteddotnet-sqldb-tutorial-master/DotNetAppSqlDb.sln file in Visual Studio.
PressF5 to run the app and open it in your default browser.
Note
If necessary,install any missing NuGet packages.
In the app, selectCreate New and create a couple ofto-do items.
Test theEdit,Details, andDelete links.
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.
In Visual StudioSolution Explorer, right-click theDotNetAppSqlDb project and selectPublish.
On thePublish screen, selectAzure as your target and selectNext.
On the next screen, make sure thatAzure App Service (Windows) is selected and selectNext.
On the nextPublish screen, sign in to your Microsoft account and the subscription you want to use.
Next toApp Service, selectCreate new.
On theApp Service (Windows) screen, configure the App ServiceName,Resource group, andHosting Plan.
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.
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.
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:
Complete theHosting Plan screen, and then selectOK.
Setting | Suggested value | For more information |
---|---|---|
App Service Plan | myAppServicePlan | App Service plans |
Location | East US | Azure regions |
Size | Free | Pricing tiers |
On theApp Service (Windows) screen, selectCreate, and wait for the Azure resources to be created.
ThePublish screen shows the resources you configured. SelectFinish, and then selectClose.
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.
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.
On theConnect to dependency screen, selectAzure SQL Database and then selectNext.
On theConfigure Azure SQL Database screen, selectCreate new.
On theAzure SQL Database screen, next toDatabase server, selectNew.
Change the server name to a value you want. The server name must be unique across all servers in Azure SQL.
SelectOK.
On theAzure SQL Database screen, keep the default generatedDatabase Name. SelectCreate and wait for the database resources to be created.
When the database resources are created, selectNext.
On theConnect to Azure SQL Database screen, selectFinish.
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.
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.
From theTools menu, selectNuGet Package Manager >Package Manager Console.
In thePackage Manager Console, install the following packages:
Install-Package Microsoft.Data.SqlClientInstall-Package Microsoft.EntityFramework.SqlServer
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.
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
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.
Inweb.config, remove theentityFramework/providers/provider
section and line:<provider invariantName="System.Data.SqlClient" .../>
.
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()); } }
Add the following attribute to theMyDatabaseContext
class declaration:
[DbConfigurationType(typeof(AppServiceConfiguration))]
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.
To test the app, add a few to-do items.
Congratulations! Your data-driven ASP.NET application is running live in Azure App Service.
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.
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.
From theView menu, selectSQL Server Object Explorer.
At the top of theSQL Server Object Explorer window, select the icon toAdd SQL Server.
On theConnect screen, your connection appears under theAzure node. Complete the information for yourServer Name,User Name,Password, andDatabase Name, and selectConnect.
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.
ExpandTables, right-click theToDoes
table, and selectView Data to interact with the database data.
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.
OpenModels\Todo.cs in the code editor. Add the following property to theToDo
class:
public bool Done { get; set; }
Run a few commands to make updates to your local database.
From theTools menu, selectNuGet Package Manager >Package Manager Console.
In the Package Manager Console window, enable Code First Migrations:
Enable-Migrations
Add a migration:
Add-Migration AddProperty
Update the local database:
Update-Database
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.
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.
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)
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>
OpenViews\Todos\Index.cshtml, and just above the empty<th></th>
element, add the following Razor code:
<th> @Html.DisplayNameFor(model => model.Done)</th>
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>
Save all files, and pressCtrl+F5 to run the app.
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.
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.
In Visual StudioSolution Explorer, right-click your project and selectPublish.
SelectMore actions >Edit to open the publish settings.
In theMyDatabaseContext dropdown, select the database connection for your Azure SQL database.
SelectExecute Code First Migrations (runs on application start), and then selectSave.
Now that you enabled Code First Migrations in your Azure app, publish your code changes.
On thePublish page, selectPublish.
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.
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.
On the Visual StudioPublish page, scroll down to theHosting section.
Select the ellipsis... at upper right and selectView streaming logs.
The logs are now streamed into theOutput 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.
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.
On the Azure portal page for your app, selectApp Service logs underMonitoring in the left menu.
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()
.
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
To stop the log-streaming service, select theStop monitoring icon in theOutput window.
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.
Go to the next tutorial to learn how to use managed identity to improve Azure SQL Database connection security.
Was this page helpful?
Was this page helpful?