Azure: Function host is not running - azure

I have a Function App in azure and when I hit the URL of the function app it says "Function host is not running." I have checked the log also in the app insights or in the Azure portal's function app service, it shows the following error message in the function app.
Note: My pipeline's Build & Releases got succeeded, so I am not sure where to check and what is the solution for this. I tried with a new function app but still no luck.
My Startup.cs file to understand How I have referred the config values,
public override void Configure(IFunctionsHostBuilder builder)
{
//var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings:DBConnection");
var serviceProvider = builder.Services.BuildServiceProvider();
_configuration = serviceProvider.GetRequiredService<IConfiguration>();
var appSettingsSection = _configuration.GetSection("AppSettings");
builder.Services.Configure<AppSettings>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSettings>();
RuntimeConfig.appsettings = appSettings;
var ConnectionString = RuntimeConfig.appsettings.AppDBConnection;
///builder.Services.AddDbContext<ShardingDbContext>(options => options.UseSqlServer(ConnectionString), ServiceLifetime.Transient);
//builder.Services.AddScoped<ITestService, TestService>();
}
public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
{
FunctionsHostBuilderContext context = builder.GetContext();
builder.ConfigurationBuilder
.AddJsonFile(Path.Combine(context.ApplicationRootPath, "local.settings.json"), optional: true, reloadOnChange: false)
.AddJsonFile(Path.Combine(context.ApplicationRootPath, $"{context.EnvironmentName}.settings.json"), optional: true, reloadOnChange: false)
.AddEnvironmentVariables();
}
I am taking the config values as IConfiguration, it works for my local but don't know how to do the same in the server.

while deploying your Function app it neither upload local.settings.json to Azure or nor makes modification on Application Settings based on local.settings.json file.
The Key-value pair related to EIA present in local.settings.json, add the same key-value pair in Azure Function App Configuration > Application Settings in the Portal.
For that we have to manually update the App Settings in portal or if you are using Visual studio, we can update using VS publish panel.
Add Application Settings using Portal
Azure Portal -> Your Azure Function -> Configuration Panel -> Application Settings/Connection Strings (Add your custom configuration)
Add Application Settings using Visual Studio Publish panel
While publishing your azure function Add your Application settings.
In a hosting panel right corner click (...).
Add your app Settings in Manage Azure App Service Settings.
Add your settings like below

Related

Getting a Connection String from Azure App Config via Configuration.GetConnectionString()

Is there a special way to define a Key Value setting for ConnectionStrings in Azure App Configuration?
I have tried using:
ConnectionStrings:DatabaseKeyName
ConnectionStrings\DatabaseKeyName
Using the standard builder.Configuration.GetConnectionString("DatabaseKeyName") always results in a null value. Using builder.Configuration["ConnectionStrings:DatabaseKeyName"] also results in null, however if I use a keyname that does not start with ConnectionStrings (e.g. Test:ConnectionStrings:DatabaseKeyName it works as an app setting via builder.Configuration["Test:ConnectionStrings:DatabaseKeyName"]
The Null value for ConnectionStrings:DatabaseKeyName indicates there is some special handling for ConnectionStrings in Azure App Config, but I don't know where I am going wrong. The Microsoft example pages don't seem to cover ConnectionStrings (except via KeyVault).
Basically I do not want to have to change this:
services.AddDbContext<IciContext>(o =>
{
o.UseSqlServer(Configuration.GetConnectionString("DatabaseKeyName"));
});
To this:
services.AddDbContext<IciContext>(o =>
{
o.UseSqlServer(builder.Configuration["DatabaseKeyName"]);
});
Standard app config connection string setting I need to simulate from Azure App Config:
{
"ConnectionStrings": {
"DatabaseKeyName": "Data Source=localhost;Initial Catalog=xxxx;Integrated Security=True"
},
In my secrets file it is in this format (which does not work with Azure App Config):
{
"ConnectionStrings:DatabaseKeyName": "Server=xxxx;Database=xxxx;User ID=xxxx;Password=xxxx"
}
To get the Connection String from Azure App Configuration, please check the below process.
Install the NuGet Package Microsoft.Azure.AppConfiguration.AspNetCore latest version to add the AddAzureAppConfiguration and read the key values.
To read Azure App Configuration locally, we need to set the secret manager to store the connection string.
dotnet user-secrets init
The above command enables the secret storage and sets the secret ID in .csproj of your application.
In Program.cs, add the below code
var myAppConn= builder.Configuration.GetConnectionString("AppConfig");
Output:
As mentioned in the MSDoc, For the Apps deployed in Azure App Service it is recommended to store Connection String in Configuration Section => Application Settings => Connection Strings of the deployed App.
Is there a special way to define a Key Value setting for ConnectionStrings in Azure App Configuration?
In Azure App Configuration => *YourAppConfiguration* => click on Configuration explorer Under Operations => click on Create => Key-value
In Program.cs, add the below code
var myconn = builder.Configuration.GetConnectionString("AppConfig");
builder.Host.ConfigureAppConfiguration(builder =>
{
builder.AddAzureAppConfiguration(myconn);
})
.ConfigureServices(services =>
{
services.AddControllersWithViews();
});
In any of the cshtml file, add the below code
#using Microsoft.Extensions.Configuration
#inject IConfiguration Configuration
<h1>#Configuration["MyConnection"]</h1>
Output for Key-Value from AppConfiguration:

Azure App Service Application Settings not overriding appsettings.json values

I have a React SPA with .Net Core WebAPI backend being deployed to Azure App Service. When developing locally i use a appsettings.json file to configure the WebAPI backend. I am setting a key/value pair for an external api called "XyzApi".
{
"XyzApi": "https://somedomain/api"
}
In a WebAPI controller I access this config setting using the Configuration provider.
var xyzApiUrl = Configuration["XyzApi"]
This works fine.
When I deploy the app to the App Service I need to change the the value of "XyzApi" to override the value from the appsettings.json with a new value. I have added a key/value pair named "XyzApi" in the App Service Application Settings section in Azure.
In the App Service documentation for Application Settings it says the value will be exposed to the configuration as an Environment Variable with the name "APPSETTING_XyzApi". It also says that it is supposed to override the value from the appsettings.json file for the key "XyzApi".
When the app spins up. The issue is that the value for "XyzApi" is still set to the value from the appsettings.json file. It is NOT being overridden. And as expected there is now a new key/value pair for "APPSETTING_XyzApi".
Why is the Azure App Service not overriding the key/value pair from the appsettings.json file with the new value configured in the Azure AppService Application Settings.
Here is the code that configures the Configuration provider.
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
});
}
All the steps you did is correct, except the appsettings' name in portal. You add "APPSETTING_XyzApi" in Configuration, which is different with "XyzApi" in appsettings.json. It would override only if the name fit.
Here is an example:
1. I set "myKey": "value1" in appsettings.json in local, And show the value on my index page.
2. After publish, I set the value to 123123:
3. The value override:

.NET Core WebJob configuration in Azure App Service

I've written web job as .NET Core Console Application (exe), that has appsettings.json.
How do I configure the WebJob in Azure? Basically I want to share some settings like connection string with the web app, that is configured trough App Service's Application Settings.
The way to get these settings from our ASP.NET Core is accessing to the injected environment variables.
Hence we have to load these environment variables into our Configuration in the Startup.cs file:
public Startup(IHostingEnvironment 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();
}
An example of appsettings.json file would be:
If you want to get the connection string named "Redis" defined in the appsettings.json file we could get it through our Configuration:
Configuration["ConnectionStrings:Redis"].
You could set this Configuration in Appsettings in webapp on azure portal:
Also we can use Configuration.GetConnectionString("Redis") to get a development connection string from our appsettings.json file and override it setting a different one in the Connection String panel of our Web App when the application is deployed and running in Azure.
For more detail, you could refer to this article.
I prefer doing this through setting environment varibles in launchSettings.json in my local project and setting the same ones in Azure App Service settings.
Advantage is that your application always uses environment variables and, more important one, no keys end up in your source control since you don't have to deploy launchSettings.json.
The CloudConfigurationManager class is perfect for this situation as it will read configuration settings from
all environments (the web jobs config and the base app config).
Install-Package Microsoft.WindowsAzure.ConfigurationManager
Then use it like this
var val = CloudConfigurationManager.GetSetting("your_appsetting_key");
The only downside is that it is only possible to read from the appSettings sections and not the connectionstring section with the CloudConfigurationManager.
If you want to share connectionsting between the web job and the base web app, then I would define the connectionstring in the appsetting section of the web app with an unique key.

Confusion between .config files and Azure settings on ASP.Net core web app

I have built a project (to provide an API to a SPA web app) as a Asp.Net Core Web Application (.net framework) with the WebApi option (VS 2017 Community). This created a project with an app.config file and no web.config file. I have a section in app.config that I read using System.Configuration.ConnectionManager.ConnectionStrings['MainDb'] in my Startup.cs class which works fine locally.
When I deploy the app to Azure and set a 'MainDb' connection string in the portal, it does not get read by the web app. I have set these via the portal directly and via the settings pane available via the Azure server explorer in VS2017. In the server explorer I can see a web.config file but no app.config file, the web.config file has no connectionstring node but the web app seems to be seeing the connection string that was in app.config when I deployed.
I am somewhat confused as to the interaction between the app.config and the web.config here - where do I need to declare my connection string so that it can be overridden by the Azure portal setting?
Typically in ASP.NET Core we use an appsettings.json file for configuration. Though there are many other options too (XML, user secrets etc.): https://joonasw.net/view/asp-net-core-1-configuration-deep-dive.
So you would have an appsettings.json file like this:
{
"ConnectionStrings": {
"MainDb": "Data Source=.;Initial Catalog=MainDb;Integrated Security=True"
}
}
You can then read it by accessing the IConfiguration object in Startup:
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
string connStr = Configuration.GetConnectionString("MainDb);
}
}
GetConnectionString("name") is actually a shorthand for Configuration.GetSection("ConnectionStrings")["name"].

Publish ASP 5 application to Azure in a custom environment

In my ASP.NET 5 (core, vNext) application I have:
appsettings.test.json
appsettings.development.json
appsettings.staging.json
appsettings.production.json
appsetings.cloud.json
Each of these include different connection strings (for different environments).
Problem
When I publish my application to Azure, it automatically uses the Production environment.
I want to use the Cloud environment, when I publish to Azure.
Note
I am using the one month free trial of Azure, which wont allow me to create deployment slots (I need to upgrade).
Question
So, is there anyways I can publish to Azure in my custom environment (Cloud) by default?
So, is there anyways I can publish to Azure in my custom environment (Cloud) by default?
Yes.
The easiest way is the Azure portal. Go to MyWebApp > Settings > Application Settings > App settings. Set the ASPNET_ENV variable to Cloud.
We can test this with a simple ASP.NET Core application.
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.AddJsonFile($"appsettings.{env.EnvironmentName}.json");
builder.Build();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Run(async (context) =>
{
await context.Response
.WriteAsync("Hello from " + env.EnvironmentName);
});
}
}
It works as expected.
Try setting ASPNET_ENV in your command line. Like set ASPNET_ENV = cloud, you can also change the environemnt in VS by right clicking on your project and selecting properties, then click debug. In the Environment vars you can edit the Hosting Environment. You can also look at this issue for more ways to change the environment.

Resources