Publish ASP 5 application to Azure in a custom environment - azure

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.

Related

Azure: Function host is not running

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

SignalR with Azure - Forced by Azure.SignalR service by default on release configuration versus debug configuration (.net core 3.1)

I have setup an App and deploying using Azure. If I deploy and connect to the Azure SignalR then it is fine, and I can manage with the Azure message limits etc. However, when I try to use the "default" SignalR from my project instead of the Azure service, the release configuration still tries to connect to the Azure one.
In my startup.cs, I am especially trying to NOT use the Azure SignalR.
services.AddSignalR();
and I have commented out this line that pointed to the Azure one:
services.AddSignalR().AddAzureSignalR("Endpoint=https://<myApp>.service.signalr.net;AccessKey=<MyKey>;Version=1.0;");
Now when I publish as a Release configuration, Azure online is trying to connect to this host:
service.signalr.net
Whilst if I publish as a Debug configuration, Azure online is connecting to the host I want:
.azurewebsites.net
Which is the one I want for now.
Am tryuing to find out which varialbe is "forcing" Azure to use his own Service.SignalR.net in release mode. Could it be some of the variable I can see on the Azure App below? or is it a setting I need to put in the Visual Studio Code?
Thx.
I believe that what you can do is something like define the env on startup to use one or another but I can't say what will be the behaviour when you will set your variables on azure.
You should try something like:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseSignalR(routes =>
{
routes.MapHub<YourHub>("/YourHub");
});
}
else
{
app.UseAzureSignalR(routes =>
{
routes.MapHub<YourHub>("/YourHub");
});
}
}

Asp.net core 2.2 variable ASPNETCORE_ENVIRONMENT not working on Azure

I am trying to find out what the problem is with my application but I always get the following error page:
I tried adding to azure the ASPNETCORE_ENVIRONMENT variable, and then restarted, but it still does not work. Am I missing smth?
I tested at my side, and the app environment was changed to development:
Then, for testing, I just throw a Exception in my code, and I will see the detailed error page:
So, I have some suggestions:
1. Check if you have saved the application settings on Azure portal. And restart the web app.
2. You can force to use development environment in startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//if (env.IsDevelopment())
//{
// app.UseDeveloperExceptionPage();
//}
// Force to use development environment
app.UseDeveloperExceptionPage();
...
}
And then re-publish it to you web app.
3. You can use remote debugging. Here is a tutorial: Troubleshoot an app in Azure App Service using Visual Studio

Azure App Service Slot - Environment.GetEnvironmentVariable() returns null

I have just created a "staging" slot in one of my Azure App Services.
In Azure Portal, inside Application Settings for that Slot, I created a new key, as follow:
...and made it a "Slot Setting" as I don't want this value to be swaped.
When I execute my code in a .NET Core project, Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") returns null. Locally it works, as soon as I set this value in my computer environment variables.
Am I missing something?
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") to get the application setting should work on the Azure WebApp. I assume that value is overridden by other codes.
You could debug it with following way.
1.Check the staging kudu(https://yousitename-staging.scm.azurewebsites.net/Env.cshtml) to check environment variable ASPNETCORE_ENVIRONMENT.
2.We also could remote debug slot with VS.
The following is my test steps:
1.Create a .net core project.
2.Create a slot for an existing Webpp and appsetting for slot
3.Check the environment variable with kudu tool
4.Add the following code in the index.chtml.cs file
var appsetting = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
ViewData["appseting"] = appsetting;
5.in the index.chtml file change the title to appsetting value
#page
#model IndexModel
#{
ViewData["Title"] = ViewData["appseting"];
}
6.Publish the WebApp to Azure with debug mode
7.Check the title of the home page.
we also could remote debug to check it.
Not sure where/how you use the Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"), but in my project I retrieve it differently. I retrieve it in the Startup.cs. Could you try something similar and see if you get it this way?
public Startup(IHostingEnvironment env, ILogger<Startup> logger)
{
var envName = env.EnvironmentName;
}
This should give you the env name in the envName variable. If this works I can help you with how you get it other places in your code.

.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.

Resources