Home > Back-end >  dotnet publish. Determ if is published version running while runtime
dotnet publish. Determ if is published version running while runtime

Time:01-06

Lets say I run

dotnet publish --configuration Release or Debug ...

Can I determ in code that this is an Published version?

I would like to have something like this.

if(<something>.IsPublished && !hostContext.HostingEnvironment.IsProduction()) throw new NotSupportedException("Published apps support only Production environment"

I'm aware of Debug,Release switches. This is not what i'm looking for.

CodePudding user response:

Creating a separate configuration other than Debug & Release would allow you to have compile-time checks. I.e. you can have code that won't even exist in your Debug/Release build.

Let's create one called Published.
Depending how you manage your projects, there are several ways to do this.


If you use VS and a solution file

Right-click on your solution, and pick Configuration Manager...
Under the Active solution configuration: dropdown, select <New...>

  • Name: Published
  • Copy settings from: Release
  • Create new project configs: ✔

If you are only using a .csproj file with no .sln

Add the following to your .csproj file:

<PropertyGroup>
  <Configurations>Debug;Release;Published</Configurations>
</PropertyGroup>

This will result in the definition of a compile-time symbol called PUBLISHED.

You can then use it in a compile-time check like so:

#if PUBLISHED
  if(!hostContext.HostingEnvironment.IsProduction())
    throw new NotSupportedException("Sorry..");
#endif

You then do your usual dotnet publish -c Published

  • Related