簡體   English   中英

部署到 Azure 時獲取 DBContext 的連接字符串

[英]Getting connection string for DBContext when deploying to Azure

編輯:這個問題已經過重大重組,現在我已經弄清楚了更多的問題,這應該可以澄清一些事情。

我正在關注本教程: https://learn.microsoft.com/en-us/azure/app-service/tutorial-do.netcore-sqldb-app

我已經部署了自己的多項目應用程序,它可以正常工作,但我無法使連接字符串正常工作。 出於某種原因,它只有在我將連接字符串硬編碼到我的 DBContext class 的 OnConfiguring 方法中時才有效。否則,它會拋出錯誤。

像這樣:

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
        .UseSqlServer(
                "Nasty hard coded azure connection string",
                providerOptions => { providerOptions.EnableRetryOnFailure(); });
    } 

但是,顯然,我想從配置文件或環境變量中獲取連接字符串。

在部署之前,我有以下內容。 用於設置連接字符串的 IServiceColleciton 的擴展方法:

public static void ConfigureSqlContext(this IServiceCollection services,
    IConfiguration configuration) =>
    services.AddDbContext<PeakedDbContext>(opts =>
 opts.UseSqlServer(configuration.GetConnectionString("defaultConnection")));

然后在program.cs中調用這個方法。 一個很正常的設置。

我還像這樣設置了一個 IDesignTimeDBContextFactory:

 public class RepositoryContextFactory : IDesignTimeDbContextFactory<PeakedDbContext>
    {
        public PeakedDbContext CreateDbContext(string[] args)
        {
            var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
            var builder = new DbContextOptionsBuilder<PeakedDbContext>()
            .UseSqlServer(configuration.GetConnectionString("defaultConnection"));
            return new PeakedDbContext(builder.Options);
        }
    }

我的 appsettings.json 和 Azure 應用服務配置都具有相同的名稱“defaultConnection”。

據我所知,這是這里推薦的方法: https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=do.net-core-cli

我還嘗試為我的 DBContext 添加一個空的構造函數。 (不確定這會如何影響事情,因為我的 DBContext 構造函數上有其他 DI。我的 DBContext 構造函數有點失控:

    public PeakedDbContext()
    {
    }

    public PeakedDbContext(DbContextOptions options) : base(options)
    {
    }

    public PeakedDbContext(DbContextOptions options, ICurrentUserService currentUserService) : base(options)
    {
        _currentUserService = currentUserService;
    }

根據上面的第二個鏈接,我的 DBContext 中不需要 OnConfiguring 方法......即使我需要,傳遞對 configuration.GetConnectionString 的訪問權限的正確方法是什么,而不是對連接字符串進行硬編碼? 我應該只添加另一個注入配置的 DBContext 構造函數嗎? 但是,它只有在我有 onconfiguring 方法時才有效。 azure 應用服務未使用上下文工廠和擴展方法設置。

它不應該使用我在上面設置的設計時工廠或主機配置擴展方法嗎? 使用 _configuration.GetConnectionString("defaultConnection") 以使其在本地和 Azure 部署上工作的正確方法是什么?

更新:仍然沒有運氣。 我嘗試將數據庫連接字符串添加為 azure 上的環境變量,如下所示: 在此處輸入圖像描述

然后更新我對 getconnection 字符串的所有引用 - 在 program.cs、IDesignFactory 和 OnConfiguring 中 - 如下所示:

Environment.GetEnvironmentVariable("PeakedDbConn")

這繼續在本地工作。 但是當部署到 Azure 時,它聲稱 null 中的連接字符串......所以它沒有看到這個變量。 我也找不到任何可以從圖像訪問 defaultConnection 的代碼。 這很奇怪,因為它可以很好地訪問 SECRET 變量。

我遵循了您提供的相同代碼,並進行了一些更改。

檢查以下步驟以從appsettings.json獲取連接字符串,如果已設置Azure App Connection String ,則覆蓋該值。

當您使用.NET Core 6時,我已經在Program.cs本身中設置了所有配置。

我的Program.cs

builder.Services.AddDbContext<MyDatabaseContext>(options =>
                    options.UseSqlServer(builder.Configuration.GetConnectionString("MyDbConnection")));
builder.Configuration.AddEnvironmentVariables();

LocalAzure App Connection Strings中必須存在相同的Connection String名稱。

我的appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "MyDbConnection": "Dummy Connection String"
  }
}

Azure 應用程序連接字符串:在此處輸入圖像描述

  • 為了檢查我們是否正在獲取Connection String值,我在 Controller 中編寫了代碼。
 private readonly IConfiguration Configuration;
 public HomeController(ILogger<HomeController> logger,IConfiguration config)
        {
            _logger = logger;
            Configuration = config;
        }
       
         public IActionResult Index()
        {
            var myconnStr = Configuration.GetConnectionString("MyDbConnection");           
            ViewBag.myconnStr = myconnStr;           
            return View();
        }

我的.csproj文件:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.AzureAppConfiguration" Version="5.2.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
  </ItemGroup>

</Project>

本地 Output:

在此處輸入圖像描述

已部署的應用程序 Output:在此處輸入圖像描述

好的,原來是 GitHub 操作才是問題所在。 我在第一個鏈接中遵循的教程沒有提到這一點,也許是因為它是一個單一的項目 api... 不太確定。

本教程使用 github 操作來構建和部署應用程序,但對我來說,在構建過程中它失敗了,說沒有連接字符串。 這是因為 GitHub 構建過程無權訪問您的本地變量或 azure 環境變量。

因此,我必須將 go 設置為我的 github 存儲庫,然后在左側單擊秘密和變量 < 操作。

單擊創建一個新的 Repository Secret,將其命名為與您的環境變量相同的名稱,即對我來說是 PEAKEDDBCONN。 然后,給它一個值。 我只是使用了我的本地主機字符串,但我想如果你願意,你可以在這里輸入“monkeynuts”,它只需要不是 null 即可。

然后,您需要在工作流 yaml 文件中添加一行,與教程中討論的相同,以告知環境變量。 我是這樣添加的:

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      PEAKEDDBCONN: ${{ secrets.PEAKEDDBCONN }}

然后一切都很好地構建並運行。

對於任何有幫助的人,我決定將整個設置寫成博客: https://garyfrewin.hashnode.dev/setting-up-an-entity-framework-core-web-api-on-azure-with-sqlserver-a-愛好項目的分步指南

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM