// Zero secrets trong code!// 1. Managed Identity (no credentials needed)// App Service / Container Apps tự động authenticate với Azure resources
builder.Configuration.AddAzureKeyVault(
new Uri("https://myapp-vault.vault.azure.net/"),
new DefaultAzureCredential()); // Uses Managed Identity in Azure, Azure CLI locally// 2. Truy cập secretsvar connectionString = builder.Configuration["ConnectionStrings:Default"];
// → Automatically pulled from Key Vault!// 3. Dùng cho mọi Azure resources
builder.Services.AddDbContext<AppDbContext>(options =>
{
// Connection string từ Key Vaultvar connStr = builder.Configuration["SqlConnectionString"];
options.UseSqlServer(connStr);
});
// Service Bus with Managed Identity (no connection string!)
builder.Services.AddMassTransit(x =>
{
x.UsingAzureServiceBus((context, cfg) =>
{
cfg.Host(new Uri("sb://myapp-bus.servicebus.windows.net"),
h => h.TokenCredential = new DefaultAzureCredential());
});
});
4. Azure Storage
csharp
// Blob Storage - files, images, documentspublicclassBlobStorageService(BlobServiceClient blobClient)
{
publicasync Task<string> UploadAsync(
Stream content, string fileName, string containerName = "uploads")
{
var container = blobClient.GetBlobContainerClient(containerName);
await container.CreateIfNotExistsAsync();
var blobName = $"{Guid.NewGuid()}/{fileName}";
var blob = container.GetBlobClient(blobName);
await blob.UploadAsync(content, new BlobHttpHeaders
{
ContentType = GetContentType(fileName)
});
return blob.Uri.ToString();
}
// Generate SAS URL cho secure downloadpublic Uri GetSecureUrl(string blobName, TimeSpan expiry)
{
var container = blobClient.GetBlobContainerClient("documents");
var blob = container.GetBlobClient(blobName);
var sasBuilder = new BlobSasBuilder
{
BlobContainerName = "documents",
BlobName = blobName,
Resource = "b",
ExpiresOn = DateTimeOffset.UtcNow.Add(expiry)
};
sasBuilder.SetPermissions(BlobSasPermissions.Read);
return blob.GenerateSasUri(sasBuilder);
}
}
// Registration
builder.Services.AddSingleton(new BlobServiceClient(
new Uri("https://myappstorage.blob.core.windows.net"),
new DefaultAzureCredential()));