Reputation: 31
I've been trying to connect my web API project to my cosmosDB instance using keyvault, but for the life of me I can't figure out how visual studio's "connected services" are supposed to be used. I figured you would just use the variables you define in the setup process, but that doesn't seem to work- my connection string and my vault connection and I wouldn't think that you would then have to do the same definitions in the appsettings.json file, because then what would the point of the connected services tab be?
If anyone could explain to me how these work, I would greatly appreciate it. Microsoft's docs seem to only explain how to create the connection, but not quite how to use the connection afterwards.
I've tried looking through microsoft's docs and multiple web tutorials, but I can't seem to make sense of it on my own.
Upvotes: 1
Views: 628
Reputation: 7347
Connected services can be any Azure Services like Azure KeyVault
, Cosmos DB
.
Follow the below steps to Add Connected Service
.
Web API
before adding service dependencies
to the Connected Services
.
Right click on the Project
folder => Add
=> Connected Service
=> click on Add a service dependency
=> select the required Service - Azure Key Vault
/ Azure Cosmos DB
.
Program.cs
.var keyVaultEndpoint = new Uri(Environment.GetEnvironmentVariable("VaultUri"));
builder.Configuration.AddAzureKeyVault(keyVaultEndpoint, new DefaultAzureCredential());
Added Azure Cosmos DB
ConnectionString
in the already added KeyVault
.
After adding service dependencies
The below packages are added in the .csproj
file
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.0.0" />
<PackageReference Include="Azure.Identity" Version="1.6.0" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.21.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Cosmos" Version="6.0.1" />
serviceDependencies.json
will be created with dependencies
.{
"dependencies": {
"secrets1": {
"type": "secrets",
"connectionId": "VaultUri",
"dynamicId": null
},
"cosmosdb1": {
"type": "cosmosdb",
"connectionId": "ConnectionStrings"
}
}
}
By using Connected Services, few configurations like adding NuGet Packages, settings in launchSettings.json
are configured by default.
In launchSettings.json
, below settings are added automatically.
I wouldn't think that you would then have to do the same definitions in the appsettings.json file, because then what would the point of the connected services tab be?
KeyVault/DB
settings in appsettings.json
and on top you have added Connected Services, then the values from appsettings.json
will be replaced with the values from Connected Services
at run time.References taken from Visual Studio Connected Services and MSDoc
Upvotes: 1