Azure API deployment issue - Swashbuckle SwaggenGen Error - c#

I've got a problem when trying to deploy my App Service to Azure from VS 2022. Each time I'm getting this error:
I'm using .NET 6 as my target framework and I've got the Swashbuckle.AspNetCore package updated to the newest version. The app service is published with success, but the error pops up when trying to update the API.
In my version of the project there is no Startup.cs but Program.cs, and the way I'm implementing the Swagger generation is:
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
I've browsed through similar posts and based on them I can add that I am not fetching any environment variables too.
I've also tried using UseSwaggerUI() like this but I get the same error anyway:
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
options.RoutePrefix = string.Empty;
});
Weird thing is that the deployment works for my colleague and it worked for me until last week when it stopped when nothing in the Program.cs was changed on the way.
My Program.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();
And my .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"
}
}
EDIT:
I've found out that the cause of the error are those lines:
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);
I've since changed them to get values directly from configuration instead of 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);
When running locally, it takes the values correctly and assignes them to the variables. But it seems that when deploying it encounters a problem with that. In line var serviceClient = new ServiceClient(CrmConnectionString); when I change the variable to static string it works correctly, but when using the variable the startup.cs error pops up (only when deploying). Same thing with initializing logger which uses the log analitycs values. Again, locally runs with no problems, only the deployment crashes.

I have created a sample ASP.NET Core 6.0 Web API and able to deploy the Application to Azure App Service without any errors.
Generally, this type of error occurs when there is any error in the code or Configuration issues.
In my version of the project there is no Startup.cs but Program.cs
.Net6 Core Folder Structure:
Yes, we need to Configure the code related to Swagger in Program.cs itself.
Check the below steps and make sure you are following the same to deploy without any issues.
Select the ASP.NET Core Web API template.
Select Enable openAPI support.
My .csproj file :
<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>
My Program.cs file :
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();
Output of Deployed Azure App Service:

Related

Azure App Service Application Setting Value not Updating

I am trying to load my appsettings.test.json file on a test API and I am having problems reading environment variables. Works fine locally but when I push it to the Azure App Service I keep getting pointed to my dev appsettings.json file.
I will attach my settings below and the API call results I used to verify this issue. Every other custom value works aside ASPNETCORE_ENVIRONMENT.
Azure App Service Application Settings
App Service Endpoint for testing
[HttpGet("env")]
public IActionResult GetEnvVariable()
{
var test = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var test1 = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
return Ok($"ASPNETCORE: {test}\nDOTNET: {test1}");
}
App Service Endpoint response
Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
}
Program.cs
public class Startup
{
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
//register bugsnag, swagger, jwt auth, auto mapper, service classes, db context, controllers
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Test API V1");
});
}
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseMiddleware<GlobalErrorHandlingMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
CSPROJ
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AssemblyName>$(MSBuildProjectName)</AssemblyName>
<RootNamespace>$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
<Configurations>Release;Debug;Test</Configurations>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<Optimize>True</Optimize>
<DefineConstants>$(DefineConstants)</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Test|AnyCPU' ">
<Optimize>True</Optimize>
<DefineConstants>$(DefineConstants)</DefineConstants>
<IntermediateOutputPath>obj\Release\net6.0</IntermediateOutputPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>$(DefineConstants)</DefineConstants>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Content Remove="appsettings.Development.json" />
<Content Remove="appsettings.json" />
<Content Remove="appsettings.Production.json" />
<Content Remove="appsettings.Test.json" />
</ItemGroup>
<ItemGroup>
<None Include="appsettings.Development.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
<None Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="appsettings.Production.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
<None Include="appsettings.Test.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Test.Api.Business\Test.Api.Business.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
</Project>
Additional Information
This app service is using the F1 free plan, could that be why?
FYI, if anyone encounters this issue. My project was originally a .NET CORE 3.1 project, even after upgrading to 6 there were obviously still lingering files which wouldn't be cleared just because I targeted a newer framework.
The culprit was my web.config file, it was overriding my ASPNETCORE_ENVIRONMENT env variable.
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
<environmentVariable name="ASPNETCORE_HTTPS_PORT" value="44364" />
<environmentVariable name="COMPLUS_ForceENC" value="1" />
</environmentVariables>

Publishing dotNet 6 SPA application on IIS server returns error: The SPA default page middleware could not return the default page '/index.html'

I am trying to publish my react redux dotnet 6 SPA app on an IIS server, but I get an error:
Error message:
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: The SPA default page middleware could not return the default page '/index.html' because it was not found, and no other middleware handled the request.
Your application is running in Production mode, so make sure it has been published, or that you have built your SPA manually.
Which I think it explains the problem but I am cannot resolve it. I tried several configs, but still I get the same error.
Here I am including my Program.cs and MyDemoProject.csproj file:
Program.cs
var spaSrcPath = "Web";
var corsPolicyName = "AllowAll";
var builder = WebApplication.CreateBuilder(args);
// Add CORS
builder.Services.AddCorsConfig(corsPolicyName);
// Register Controllers
builder.Services.AddControllers();
// Add Brotli/Gzip response compression (prod only)
builder.Services.AddResponseCompressionConfig(builder.Configuration);
builder.Services.AddMvc(opt => opt.SuppressAsyncSuffixInActionNames = false);
// In production, the Vue files will be served from this directory
builder.Services.AddSpaStaticFiles(opt => opt.RootPath = $"{spaSrcPath}/dist");
// Register the Swagger services (using OpenApi 3.0)
builder.Services.AddOpenApiDocument(settings =>
{
settings.Version = "v1";
settings.Title = "My Demo Project API";
settings.Description = "Documentation of the api ....";
});
var app = builder.Build();
// If development, enable Hot Module Replacement
// If production, enable Brotli/Gzip response compression & strict transport security headers
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseResponseCompression();
app.UseExceptionHandler("/Error");
app.UseHsts();
}
// Global exception handling
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
var error = context.Features.Get<IExceptionHandlerFeature>();
var exDetails = new ExceptionDetails((int)HttpStatusCode.InternalServerError, error?.Error.Message ?? "");
context.Response.ContentType = "application/json";
context.Response.StatusCode = exDetails.StatusCode;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Application-Error", exDetails.Message);
context.Response.Headers.Add("Access-Control-Expose-Headers", "Application-Error");
await context.Response.WriteAsync(exDetails.ToString());
});
});
app.UseCors(corsPolicyName);
app.UseOpenApi();
app.UseSwaggerUi3();
app.UseHttpsRedirection();
app.UseSpaStaticFiles(new StaticFileOptions { RequestPath = $"/{spaSrcPath}/build" });
app.UseSpaStaticFiles();
app.UseRouting();
// Map controllers
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = spaSrcPath;
if (app.Environment.IsDevelopment())
spa.UseReactDevelopmentServer(npmScript: "start");
});
app.Run();
MyDemoProject.csproj file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
<TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
<IsPackable>false</IsPackable>
<SpaRoot>Web\</SpaRoot>
<DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
<AssemblyName>MyDemoProject</AssemblyName>
<RootNamespace>MyDemoProject</RootNamespace>
<EnableNETAnalyzers>False</EnableNETAnalyzers>
</PropertyGroup>
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="6.0.2" />
<PackageReference Include="Microsoft.TypeScript.MSBuild" Version="4.6.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="NSwag.AspNetCore" Version="13.15.10" />
<PackageReference Include="NSwag.MSBuild" Version="13.15.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Content Remove="$(SpaRoot)**" />
<None Remove="$(SpaRoot)**" />
<None Include="$(SpaRoot)**" CopyToPublishDirectory="PreserveNewest" Exclude="$(SpaRoot)node_modules\**;$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder);#(Content)" />
</ItemGroup>
<Target Name="NSwag" AfterTargets="Build" Condition="'$(Configuration)' == 'Debug'">
<Copy SourceFiles="#(Reference)" DestinationFolder="$(OutDir)References" />
<Exec Command="$(NSwagExe_Net60) run /variables:Configuration=$(Configuration) /runtime:Net60" />
<RemoveDir Directories="$(OutDir)References" />
</Target>
<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
<!-- Ensure Node.js is installed -->
<Exec Command="node --version" ContinueOnError="true">
<Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
</Exec>
<Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
<Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install --force" />
<!-- Updated to react 18.0, should not interfere with the build process -->
</Target>
<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
<!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install --force" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build --prod" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:ssr -- --prod" Condition=" '$(BuildServerSideRenderer)' == 'true' " />
<!-- Include the newly-built files in the publish output -->
<ItemGroup>
<DistFiles Include="$(SpaRoot)build\**" />
<DistFiles Include="$(SpaRoot)node_modules\**" Condition="'$(BuildServerSideRenderer)' == 'true'" />
<ResolvedFileToPublish Include="#(DistFiles->'%(FullPath)')" Exclude="#(ResolvedFileToPublish)">
<RelativePath>%(DistFiles.Identity)</RelativePath>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
</Project>
And I am using command below to build and publish the app:
dotnet publish --arch x64
And this is my folder structure, I am including the folders and files that I think are relevant to my problem:
MyDemoProject
Backend
Base
Program.cs
Models
Services
Web
build
node_modules
public
index.html
src
App.tsx
index.tsx
appsettings.json
MyDemoProject.csproj
web.config
Mobile
...
...
...
MyProject.sln

Azure Function can't connect to azure sql database. Package error

I'm trying to connect my azure function to my azure sql database. When trying connection.open() it gives the following error.
Executed 'ClientID2' (Failed, Id=22ad8465-45f5-4fff-ba90-f0ff7d0ee465,
Duration=5895ms) [2021-11-25T10:49:57.575Z] System.Private.CoreLib:
Exception while executing function: ClientID2.
Microsoft.Data.SqlClient: The type initializer for
'Microsoft.Data.SqlClient.TdsParser' threw an exception.
Microsoft.Data.SqlClient: Could not load file or assembly
'System.Text.Encoding.CodePages, Version=5.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'.
The connection itself runs on .net 5.0 framework, but not in .net core 3.1 .
[FunctionName("ClientID2")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log)
{
string requestBody = string.Empty;
try
{
log.LogInformation("Function process");
using (SqlConnection connection = new SqlConnection(Environment.GetEnvironmentVariable("Connection_Database")))
{
connection.Open();
Packages installed
Can anyone point me in the right direction?
Best regards
EDIT:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
<RootNamespace>Client_ID</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.30" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Http" Version="3.0.12" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="4.0.0" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
Local.Settings.Json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"Connection_Database": Connection string from azure sql database
}
}
I figured it out, but not sure if it is the correct way.
Had to put the System.Text.Encoding.CodePages.dll and System.Runtime.CompilerServices.Unsafe.dll directly in bin folder of project.
Next, according to this answer
I added to the .csproj the following
<ItemGroup>
<FunctionsPreservedDependencies Include="System.Text.Encoding.CodePages.dll" />
<FunctionsPreservedDependencies Include="System.Runtime.CompilerServices.Unsafe.dll" />
</ItemGroup>
And then it worked

ASP.NET API failing to publish on azure

I'm trying to publish an C# API to azure, I followed all the steps in this documentation here but for some reason when I publish the application the build succeeds and crashes when this below line gets executed
Generating swagger file to 'C:\Users\user\Projs\API\bin\Release\netcoreapp3.1\swagger.json'.
and the only error log that gets printed is
Failed to generate swagger file. Error dotnet swagger tofile --serializeasv2 --output "C:\Users\user\Downloads\Projs\API\bin\Release\netcoreapp3.1\swagger.json" "C:\Users\user\Downloads\Projs\API\bin\Release\netcoreapp3.1\API.dll" v1
Unhandled exception. System.IO.FileLoadException: Could not load file or assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)
File name: 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
Be sure that the Startup.cs for your application is calling AddSwaggerGen from within ConfigureServices in order to generate swagger file. Visit https://go.microsoft.com/fwlink/?LinkId=2131205&CLCID=0x409 for more information.
This is my startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc(
"v1",
new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My API", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseSwagger(c =>
{
c.SerializeAsV2 = true;
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("v1/swagger.json", "MyAPI V1");
});
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
This is my .csproj file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseNETCoreGenerator>true</UseNETCoreGenerator>
<UserSecretsId>d844b2a8-00b0-473d-8f97-9dca9f2899bd</UserSecretsId>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'net45'">
<AutoGenerateBindingRedirects>false</AutoGenerateBindingRedirects>
</PropertyGroup>
<ItemGroup>
<Folder Include="Model\" />
<Folder Include="Context\" />
<Folder Include="Contracts\ServiceResponse\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNet.SignalR" Version="2.4.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.13" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="AutoMapper" Version="10.1.1" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.2.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
<PackageReference Include="System.Runtime" Version="4.3.1" />
</ItemGroup>
</Project>
I have tried solutions from these links but none of them worked
Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies
https://github.com/Azure/azure-functions-vs-build-sdk/issues/160
Could not load file or assembly 'System.Runtime, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
Is there a way to fix this?
Update:
I tried a solution that was told by a user in the thread to add binding redirects, I added a web.config and a app.config and added the bindinds but it still fails to publish
Update 2:
I couldn't find a solution so I installed .net 5.0 and it worked
You can use the latest version of Swashbuckle.AspNetCore. I found the official workaround here from Swashbuckle on GitHub:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/2006
Add a global.json file to your Web API project
Put this in it:
{
"sdk": {
"version": "3.1.406",
"rollForward": "latestPatch"
}
}

An error occurred while accessing the Microsoft.Extensions.Hosting services when adding or updating migration

I have downloaded one of my old projects and when I tried to run the Update-Database from the Package Manager Console I get the following message
Build started... Build succeeded. An error occurred while accessing
the Microsoft.Extensions.Hosting services. Continuing without the
application service provider. Error: Value cannot be null. (Parameter
's') No DbContext was found in assembly 'BusinessLogicLayer'. Ensure
that you're using the correct assembly and that the type is neither
abstract nor generic.
The difference between now and when I have used the application last time is that I have reset windows, and reinstalled all the programs back.
The application runs normally and I managed to add the migrations using
CreateHostBuilder(args)
.Build()
.MigrateDatabase<DataContext>()
.Run();
and all tables have been created and populated with the seed data.
The last time I have been working on this project everything was working just fine.
This is how I connect to the DB
services.AddDbContext<DataContext>(optionsBuilder =>
optionsBuilder.UseNpgsql("User ID=postgres;Password=my_actual_pass;Server=localhost;Port=5432;Database=medication_platform3;Integrated Security=true;Pooling=true;"));
Constructor for DataContext
public DataContext(DbContextOptions<DataContext> options)
: base(options) { }
DataAccessLayer
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Migrations\**" />
<EmbeddedResource Remove="Migrations\**" />
<None Remove="Migrations\**" />
</ItemGroup>
<ItemGroup>
<Compile Include="Migrations\20201207230245_InitialMigration.cs" />
<Compile Include="Migrations\20201207230245_InitialMigration.Designer.cs" />
<Compile Include="Migrations\DataContextModelSnapshot.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Identity.Core" Version="5.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BusinessObjectLayer\BusinessObjectLayer.csproj" />
</ItemGroup>
</Project>
appsettings.json
{
"JwtKey": "SOME_RANDOM_KEY_DO_NOT_SHARE",
"JwtIssuer": "http://localhost:5001",
"JwtExpireDays": 1,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
I can provide more information if needed.
After using update-database -verbose
I was able to track the line with the problem.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
int port = int.Parse(Environment.GetEnvironmentVariable("PORT"));
....
}
This was a configuration made for the deployment and I forgot to change this line to
int port= 5001

Categories

Resources