.NET Core WebJob configuration in Azure App Service - azure

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.

Related

How to use Azure App Settings in a Blazor WebAssembly Client side application at runtime as appsettings.json configuration?

I'm Working on Blazor WebAssembly Client/Server project (directory structure as above)
Have some application settings in both client and server projects.
The projects are hosted in Azure.
The problem is in the Client side with the appsettings.json
In the client side, the appsettings.json is within the wwwroot directory. It is okay to access the file within the app, However, the settings cannot be overwritten by Azure Portal Application Settings of the App service.
It means, that after the app is deployed in Azure portal on a Web App Service, my configuration settings do not work with the application settings' variables.
This is the code in the Progam.cs, which works fine and read the configuration from the file, but ignores the configuration settings of the Web App Service on Azure.
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
//Add a named httpClient and set base Address and Default Request Headers
builder.Services.AddHttpClient("SOME_WEB_URL", client => // SOME_WEB_URL is defined in the appsettings.json or in the Azure App Service configuration (Application Settings)
{
client.BaseAddress = new Uri(builder.Configuration["sbformsapi"]);
});
//Add a named httpClient and set base Address and Default Request Headers
builder.Services.AddHttpClient("WEB_APP_API", client => // WEB_APP_API is defined in the
{
client.BaseAddress = new Uri(builder.Configuration["sbwebappapi"]);
});
builder.Services.AddAuthorizationCore();
....
await builder.Build().RunAsync();
}
Could someone please guide how can I either
set the appsettings.json file outside the wwwroot and read it from there?
OR
inject/use the values from Azure App Service configuration's Application settings at runtime?
I am talking about the application settings here (as in the pic)...
Currently application settings are only available for the backend API associated with your Blazor App (assuming using Static App?).
https://learn.microsoft.com/en-gb/azure/static-web-apps/application-settings
So, looking at the Blazor docs, I don't think it is possible to load Azure App Settings directly in a WebAssembly. You can look for yourself
https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-6.0
I suggest instead to put the backend URL in the appsettings.json and then use a backend service to load the configuration information from there.

Should I create my own settings.json in an Azure Function project?

We have an Azure Function project which requires parameters. At the moment, these parameters are stored in Azure Function's application Setting.
To run the azure function locally, we used to do this:
var id = GetEnvironmentVariable("Id");
///var id=12345;
Basically on local machine, we will just uncomment the hard coded line to get the value;
I don't really like it, so I did this:
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("settings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
I put all settings into a settings.json and read it from there.
However, as these settings are already available in azure function's appsetting section, I will have to manually delete them from azure portal (or change the arm template).
What is the preferred way to store settings for azure function? In appsetting section or in a config file like I did? Or maybe some different way?
In fact, as Carlos Alves Jorge says, the function app will read settings from local.settings.json on local by default. And on azure it will read settings from configuration settings by default.
By default, publication neither upload local.settings.json to Azure, nor makes modification on Application settings based on that local file, hence we need to update them manually on Azure portal.
If you are using VS to publish your azure function, there is a easy way to change the settings from local to azure.(edit the publish profile.)

how to override local connection string with azure connection string

I am using appsettings.json in .Net core project for connection string. My connection string is :
"ConnectionStrings": {
"OT_DB_Connection": "Data Source=108.***.**.**;Initial Catalog=O*******s;User ID=O*******s;Password=O*********$"
},
In startup.cs i am accessing connection string with key like this
options.UseSqlServer(Configuration.GetConnectionString("OT_DB_Connection"));
I deployed this code on azure and i have sql database on azure.
After deployment how my website will use the connection string of azure ?
How to override the local connection string with azure connection string at run time.
You should read the following article:
Multiple Environment Configuration Files in ASP.NET Core
You can have multiple appSettings e.g. 1 for you local environment and 1 for Azure etc. When you publish your app to Azure, you can add an application setting called ASPNETCORE_ENVIRONMENT and add a value that maps to your environment for your app to pick up the correct configuration. If you have an appSettings.Azure.json file you can set ASPNETCORE_ENVIRONMENT to Azure and it will use that configuration file.
If you do not want to take this approach, you can also override the connection string directly in Azure as show in the picture below. This is accessible under your app service -> Application Settings -> Connection Strings. You will want to override OT_DB_Connection.

.NET Core - Set Environment Variable in Azure Deployment Task

I'm currently trying to use the launchSettings.json file to manage the environment variables of the application, so my Setup.cs file can manage the environments in the way of env.IsDevelopmentEnvironment(), etc.
In VSTS, how do I go about setting the environment variable ASPNETCORE_ENVIRONMENT on an Azure Deployment task? Or should it get in the dotnet publish task I've got in my build steps?
Because ASPNETCORE_ENVIRONMENT is an environment variable, you can just specify it on Azure.
See the Stack Overflow answer on How and where to define an environment variable on Azure.
If you want to keep your deployment process idempotent, I'd suggest using this deployment step to set on the Azure Web App.
https://marketplace.visualstudio.com/items?itemName=pascalnaber.PascalNaber-Xpirit-WebAppConfiguration
Technically it adds release settings to the web.config as well, which isn't necessary for a core app, but importantly, it also sets the Environment Variables for the Azure host.
Provided you have specified to use environment variables in your Startup.cs:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables(); //override settings with environment variables
var config = builder.Build();
Configuration = config;
}
So if you have a release variable: appsetting.ASPNETCORE_ENVIRONMENT = Release, you will find that $env:ASPNETCORE_ENVIRONMENT will indeed be "Release" if you're checking via the PowerShell console on Kudu.
I'm actualy using this extension to override all of my appsettings.json variables as well as ASPNETCORE_ENVIRONMENT at release-time instead of tokenzing some appsettings.{environment}.json file. I can just override with environment variables by using the right naming convention in my VSTS Release Variable names.
For example, if my appsettings.json has this structure:
{
settings: {
secret: {
foo: "bar"
}
}
}
I can override with a release variable such as:
appsetting.settings:secret:foo = "bar"
Then go check $env:settings:secret:foo on the Azure Web App after deployment
Without doing anything additional in my source or uzipping a web deployment package, tokenizing a config file and then re-zipping prior to msdeploy, I've got enviornment-specific configurations.
You can install the Replace Token extension and then add a Replace Token task in your build/release definition. This task could replace the strings in a file with the variable value you added in the build/release definition.

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