DrewB
DrewB

Reputation: 1536

Preprocessor directives per launch settings in .Net Core

I have a .net core 1.1 web app that I am working on with my team. In some cases, we need to debug the app using IIS Express and in other cases we need to use the WebListener instead. Since the WebListner commands will cause the app to crash if it is run under IIS Express, I would like to use preprocessor directives to disable this when the app is being run under IIS Express. The code would look something like this:

   #if !RUNNING_UNDER_IIS_EXPRESS
   .UseWebListener(options =>
    {
        options.ListenerSettings.Authentication.Schemes = AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM;
        options.ListenerSettings.Authentication.AllowAnonymous = false;
    })
#endif

Can anyone tell me how I can set this up or suggest a better way of doing the whole thing?

Upvotes: 3

Views: 1662

Answers (1)

Maximilian Ast
Maximilian Ast

Reputation: 3499

The problem with your question is that a preprocessor directive is used and evaluated at compile time, not run time. So if you want a "easy" switch, you have to define it in your csproj as a build configuration. You have to add a build configuration to your csproj file:

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='WebListener|AnyCPU'">
    <DefineConstants>DEBUG</DefineConstants>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='IISExpress|AnyCPU'">
    <DefineConstants>DEBUG</DefineConstants>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
</PropertyGroup>

And you have to add the information, which build configurations are awailable:

<PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <Configurations>Debug;Release;WebListener;IISExpress</Configurations>
</PropertyGroup>

so you can use your code as example

#if WEBLISTENER
    .UseWebListener(options =>
    {
        options.ListenerSettings.Authentication.Schemes = AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM;
        options.ListenerSettings.Authentication.AllowAnonymous = false;
    })
#endif

#if IISEXPRESS
    /* ... */
#endif

BUT: With this solution you have to change both, the launch settings AND the build settings, to switch between your configurations:

Build + Launch Configurations

For more information you can look into these ressources:

Upvotes: 4

Related Questions