.Net Core 中每个启动设置的预处理器指令

Preprocessor directives per launch settings in .Net Core

我有一个 .net core 1.1 网络应用程序,我正在与我的团队合作。在某些情况下,我们需要使用 IIS Express 调试应用程序,而在其他情况下,我们需要改用 WebListener。由于 WebListner 命令将导致应用程序在 IIS Express 下 运行 下崩溃,因此当应用程序在 IIS Express 下 运行 时,我想使用预处理器指令禁用它。代码看起来像这样:

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

任何人都可以告诉我如何设置它或建议一个更好的方法来完成整个事情吗?

您的问题是在编译时使用和评估预处理器指令,而不是 运行 时。所以如果你想要一个 "easy" 开关,你必须在你的 csproj 中将它定义为构建配置。您必须向 csproj 文件添加构建配置:

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

并且您必须添加可用的构建配置信息:

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

因此您可以使用您的代码作为示例

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

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

但是:使用此解决方案,您必须同时更改启动设置和构建设置,以在您的配置之间切换:

有关更多信息,您可以查看这些资源: