避免使用新的 csproj 格式设置复制到输出目录

Avoid to set Copy To Output Directory with new csproj format

我使用 "new" csproj 格式创建了一个 VS2017 解决方案,它是一个使用 Nancyfx 编写的 web .net 4.6.1 应用程序,通过 owin 和 IIS 提供页面。

我所有的视图都在 Views 文件夹下,但如果我不设置 Copy to Output 选项,IIS 无法找到它们(我的自定义配置文件也是如此)。

我认为问题是输出目录自动设置为 bin\net461\win7-x86 而不是简单地 bin 并且 Web 应用程序的工作目录设置为输出目录,所以我必须设置 copy to output 选项。

如何使用新的 csproj 格式,同时保留编辑视图文件的能力而无需重建应用程序?我已经尝试将输出文件夹设置为 bin 但它被忽略了。我还尝试在调试选项卡中设置工作目录值,但无济于事。我在每个配置中都设置了值 (debug/release),所以这不是问题。

这是我的 csproj 文件:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <RuntimeIdentifier>win7-x86</RuntimeIdentifier>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x86'" />

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Owin" Version="1.1.2" />
    <PackageReference Include="MongoDB.Driver" Version="2.4.4" />
    <PackageReference Include="Nancy" Version="2.0.0-clinteastwood" />
    <PackageReference Include="Nancy.Authentication.Forms" Version="2.0.0-clinteastwood" />
    <PackageReference Include="Nancy.Authentication.Stateless" Version="2.0.0-clinteastwood" />
    <PackageReference Include="Nancy.Bootstrappers.Unity" Version="2.0.0-clinteastwood" />
    <PackageReference Include="Nancy.Serialization.JsonNet" Version="2.0.0-clinteastwood" />
    <PackageReference Include="Nancy.Validation.FluentValidation" Version="2.0.0-clinteastwood" />
    <PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="Views\*.sshtml">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Configuration" />
  </ItemGroup>

</Project>

经过两天的尝试,我找到了问题的根本原因:这不是 VS/csproj 问题,而是 Nancyfx 2.0 配置问题。

对于这里感兴趣的每个人,我都遵循了解决问题的步骤:

  • 实施一个 IRootPathProvider 配置为 return 从您的 Startup class
  • 中获取的 IHostingEnvironment.ContentRootPath 的值
  • 在您的 Bootstrapper 覆盖 IRootPathProvider RootPathProvider { get; }
  • 中注册自定义 IRootPathProvider
  • 默认情况下,在 Nancyfx 2.0 中,视图 始终 缓存,即使在调试模式下 (see this ticket),因此在您的 Bootstrapper 中覆盖配置方法如下图

方法Bootstrapper.Configure:

public override void Configure(INancyEnvironment environment)
{
    base.Configure(environment);
#if DEBUG
    // Disable view caching in debug mode
    environment.Views(true, true);
#endif
}

现在视图是从 VS 项目目录(而不是 bin 文件夹)中读取的,并且不会被缓存,因此在每次视图更改之间不再需要重建。在您的 csproj 中,您可以轻松地输入:

<None Include="Views\**\*.sshtml" />