swagger Azure API部署问题- Swashbuckle SwaggenGen错误

wxclj1h5  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(208)

尝试将我的应用服务从VS 2022部署到Azure时遇到问题。每次我都收到此错误:

我的目标框架是.NET 6,Swashbuckle.AspNetCore包更新到最新版本,应用服务发布成功,但尝试更新API时弹出错误。
在我的项目版本中,没有Startup.cs,只有Program.cs,我实现Swagger生成的方式是:

builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();

我浏览过类似的帖子,基于它们,我可以补充说,我也没有获取任何环境变量。
我也试过像这样使用UseSwaggerUI(),但还是得到了同样的错误:

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
    options.RoutePrefix = string.Empty;
});

奇怪的是,部署对我的同事很有效,对我也很有效,直到上周,当Program.cs中的任何内容都没有更改时,部署停止了。
我的程序.cs:

var builder = WebApplication.CreateBuilder(args);
var azureKeyVaultUrl = builder.Configuration[AppConfigurationConst.AzureKeyVaultUrl];
var logAnalyticsWorkspaceId = AzureKeyVaultHelper.GetAzureKeyVault(azureKeyVaultUrl, AppConfigurationConst.LogAnalyticsWorkspaceId);
var logAnaliticsAuthenticationId = AzureKeyVaultHelper.GetAzureKeyVault(azureKeyVaultUrl, AppConfigurationConst.LogAnaliticsAuthenticationId);
var CrmConnectionString = AzureKeyVaultHelper.GetAzureKeyVault(azureKeyVaultUrl, AppConfigurationConst.OneCrmConnectionString);

var logger = new LoggerConfiguration()
               .WriteTo.AzureAnalytics(logAnalyticsWorkspaceId, logAnaliticsAuthenticationId)
               .Enrich.FromLogContext()
               .CreateLogger();

var serviceClient = new ServiceClient(CrmConnectionString);

builder.Logging.AddSerilog(logger);

logger.Information("Start ALGOI App Service");

builder.Services.AddControllers().AddNewtonsoftJson();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddSingleton<IAuthenticationService, AuthenticationService>();
builder.Services.AddSingleton<IWebClientService, WebClientService>();

builder.Services.AddScoped<ICreateSessionService, CreateSessionService>();
builder.Services.AddScoped<ICreateFolderService, CreateFolderService>();
builder.Services.AddScoped<IDeleteFolderService, DeleteFolderService>();

builder.Services.AddScoped<IVerifyFolderService, VerifyFolderService>();
builder.Services.AddScoped<IUndoFolderService, UndoFolderService>();

builder.Services.AddSingleton(serviceClient);
builder.Services.AddApplicationInsightsTelemetry(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]);

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

以及我的.csproj:

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

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UserSecretsId>{usersecretsid}</UserSecretsId>
    <GenerateRuntimeConfigurationFiles>True</GenerateRuntimeConfigurationFiles>
  </PropertyGroup>

  <ItemGroup>
    <Compile Remove="Connected Services\**" />
    <Content Remove="Connected Services\**" />
    <EmbeddedResource Remove="Connected Services\**" />
    <None Remove="Connected Services\**" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="FluentAssertions" Version="6.7.0" />
    <PackageReference Include="JsonSubTypes" Version="1.9.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.15.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.6" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.6" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.7" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.6">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Graph" Version="4.34.0" />
    <PackageReference Include="Microsoft.Identity.Client" Version="4.48.1" />
    <PackageReference Include="Microsoft.Identity.Web" Version="1.16.0" />
    <PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="1.16.0" />
    <PackageReference Include="Microsoft.PowerPlatform.Dataverse.Client" Version="1.0.9" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.6" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
    <PackageReference Include="Polly" Version="7.2.3" />
    <PackageReference Include="RestSharp" Version="106.13.0" />
    <PackageReference Include="Serilog" Version="2.11.0" />
    <PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.0" />
    <PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.AzureAnalytics" Version="4.8.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
    <PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
    <PackageReference Include="System.Net.Http" Version="4.3.4" />
    <PackageReference Include="TypeSafe.Http.Net.HttpClient" Version="2.2.16" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="someprojectpath" />
    <ProjectReference Include="someprojectpath" />
    <ProjectReference Include="someprojectpath" />
  </ItemGroup>

  <ItemGroup>
    <Content Update="local.settings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

</Project>

appsettings.json:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "domain",
    "TenantId": "tenantid",
    "ClientId": "clientid",
    "Scopes": "access_as_user",
    "CallbackPath": "/signin-oidc",
    "ClientSecret": "Client secret from app-registration. Check user secrets/azure portal.",
    "ClientCertificates": []
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AzureKeyVaultUrl": "keyvaulturl",
  "AllowedHosts": "*",
  "MicrosoftGraph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "user.read"
  },
  "ApplicationInsights": {
    "ConnectionString": "appinsightsconnectionstring"
  }
}

编辑:我发现错误的原因是这些行:

var azureKeyVaultUrl = builder.Configuration[AppConfigurationConst.AzureKeyVaultUrl];
var logAnalyticsWorkspaceId = AzureKeyVaultHelper.GetAzureKeyVault(azureKeyVaultUrl, AppConfigurationConst.LogAnalyticsWorkspaceId);
var logAnaliticsAuthenticationId = AzureKeyVaultHelper.GetAzureKeyVault(azureKeyVaultUrl, AppConfigurationConst.LogAnaliticsAuthenticationId);
var CrmConnectionString = AzureKeyVaultHelper.GetAzureKeyVault(azureKeyVaultUrl, AppConfigurationConst.OneCrmConnectionString);

我已经将它们更改为直接从配置而不是keyvault获取值:

var azureKeyVaultUrl = builder.Configuration.GetValue<string>(AppConfigurationConst.AzureKeyVaultUrl);
var logAnalyticsWorkspaceId = builder.Configuration.GetValue<string>(AppConfigurationConst.LogAnalyticsWorkspaceId);
var logAnaliticsAuthenticationId = builder.Configuration.GetValue<string>(AppConfigurationConst.LogAnaliticsAuthenticationId);
var CrmConnectionString = builder.Configuration.GetValue<string>(AppConfigurationConst.OneCrmConnectionString);

在本地运行时,它正确地获取值并将其赋值给变量。但在部署时,它似乎遇到了一个问题。在var serviceClient = new ServiceClient(CrmConnectionString);行中,当我将变量更改为静态字符串时,它工作正常,但在使用变量时,弹出startup.cs错误(仅在部署时)。初始化日志记录器也是如此,它使用日志分析值。同样,本地运行没有问题,只是部署崩溃。

vlju58qv

vlju58qv1#

我已经创建了一个示例ASP.NET Core 6.0 Web API,并且能够将应用程序部署到Azure App Service,没有任何错误。
通常,当代码中存在任何错误或配置问题时,就会发生此类错误。
在我的项目版本中,没有Startup.cs,只有Program.cs

.Net6 Core文件夹结构:

是的,我们需要在Program.cs本身中ConfigureSwagger相关的代码。
检查以下步骤,并确保您按照相同的步骤进行部署,没有任何问题。

  • 选择ASP.NET Core Web API模板。

  • 选择Enable openAPI support .

我的.csproj文件:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>
</Project>

我的Program.cs文件:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
else
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
        options.RoutePrefix = string.Empty;
    });
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

已部署Azure应用服务的输出:

相关问题