Is it possible to get environment variable from webapp coming from webjob

2k Views Asked by At

I have a problem with reading environment variables. I have 2 projects under same solution. Basic i need to be able to read my environment Variables when i come from my webjob.

The two project are a asp.net-core-mvc project and a .net core console project.

My console project is a "Webjob" with a reference to my web app project.

When my "Webjob" is running, it hits a method in my web app. Then i tries to get the environment variables from my web app. Which returns null, becouse it is not set.

Is there any way to run it so i can get the environment varaible from my web app when i come from my webjob?

the code i run to get the variables when my web app is running alone is

var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
2

There are 2 best solutions below

2
On

You cannot, nor should you, reference an ASP.NET Core project from another project and directly hit actions as if they were methods. You need to start the ASP.NET Core project and have it running, and then make requests to it from your console app using HttpClient. Otherwise, none of the stuff in Startup happens (because it's not running), and as a result, you have no access to services such as configuration.

2
On

When you say "it hits a method in my web app", I assume you mean you run a method in your WebApp project, and not call a WebAPI endpoint.

The thing is that the debug configuration of VS is applicable only to the project running the actual code, just like the web.config or app.config can be found in that particular project's bin/debug folder. This means you would need to set the environment variables on the WebJob project as well when running that project.

However: when deploying to Azure for example, you will typically host both projects in the same App Service, which share configuration, and so can read from the same values.