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>
Related
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:
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
I am getting error in my .NET 5.0 framework Azure durable function project in VS2019
'IServiceCollection' does not contain a definition for 'AddPolicyHandler' and the best extension method overload 'PollyHttpClientBuilderExtensions.AddPolicyHandler(IHttpClientBuilder, IAsyncPolicy)' requires a receiver of type 'IHttpClientBuilder'
.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="IdentityModel" Version="4.2.0" />
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.15.0" />
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.DurableTask" Version="2.5.1" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.ServiceBus" Version="4.3.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="3.1.0" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.13" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
Startup.cs
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Polly;
using Polly.Extensions.Http;
using System;
using System.Net.Http;
namespace Itel.DeliveryOrchestration
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient()
.AddPolicyHandler(GetRetryPolicy());
}
private IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
.WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}
}
}
As I can see (based on the provided code sample) you have used the wrong Polly - HttpClient integration nuget package
using Polly.Extensions.Http;
builder.Services.AddHttpClient()
.AddPolicyHandler(GetRetryPolicy());
The Polly.Extensions.Http is deprecated and not updated anymore
You should prefer to use Microsoft.Extensions.Http.Polly package instead
Posting suggestion provided by #Nkosi in the comments as an answer so that it will be helpful for other community members who face similar kind of issues.
AddHttpClient with no arguments returns IServiceCollection while AddPolicyHandler applies to IHttpClientBuilder. You will need to use a named client
public static IServiceCollection AddHttpClient(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
//...
Referenced source code HttpClientFactoryServiceCollectionExtensions
When I send an HTTP request to the function, It shows this error on console output, and returns HTTP 500 status code without hitting the the break point of function's first line.
Executed 'Validate' (Failed, Id=548b4612-42f8-4e49-886a-da6888045c32,
Duration=343ms) System.Net.Primitives: Value cannot be null.
(Parameter 'host') An unhandled host error has occurred.
System.Net.Primitives: Value cannot be null. (Parameter 'host').
Function
[FunctionName("Validate")]
public async Task Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] string req,
[SignalR(HubName = "PubSub")] IAsyncCollector<SignalRMessage> signalRMessageQueue)
{
...
}
host.json
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingExcludedTypes": "Request",
"samplingSettings": {
"isEnabled": true
}
}
}
.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
<RootNamespace>ZulaMobile.Lobby.StoreValidation</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.30" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SignalRService" Version="1.6.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="3.1.21" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\zulamobile-azure-lobby-common\zulamobile-azure-lobby-common.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="Functions\CafeBazaar\" />
<Folder Include="Huawei\" />
</ItemGroup>
</Project>
I tried to reproduce the same issue but it worked fine at my end.
Followed by this MS DOC & demo GitHub project ,
Created a Signal IR in Azure portal .
Open the download folder from my VS Code-
And added the following packages into my local here is my .csproj file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SignalRService" Version="1.6.0" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
</ItemGroup>
<ItemGroup>
<None Update="content\index.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
And make sure that you have added your connection string in your local settings.json which have to copy from portal from Azure signalIR > Keys>Connection string.
Here are some screenshot for reference output:
Note: If still facing the same issue you can try to Un install the Azure function V3 and install it again .
For more information please refer this SO THREAD .
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