razor - 确保将所有* .cshtml文件设置为 “Content”进行构建操作

标签 razor visual-studio-2013 msbuild asp.net-mvc-5 webdeploy

当我复制粘贴*.cshtml文件几次时,Visual Studio由于某种原因将这些文件上的Build Action设置为“None”:

由于存在文件,因此无法检测到何时在本地工作。但是,当您通过WebDeploy进行部署时,在“构建操作”上标记为“无”的文件将不会打包。结果,我在服务器上得到了无法正常工作的应用程序。

问题:有没有一种方法可以自动检测到这种情况并进行预防?

最佳答案

您可以使用一个小的代码段扩展.csproj,当“无”组中的项目具有扩展名.cshtml时,该代码段将生成警告。该代码段将是:

<Target Name="EnsureContentOnViews" BeforeTargets="BeforeBuild">
  <ItemGroup>
    <Filtered Include="@(None)" Condition="'%(Extension)' == '.cshtml'" />
  </ItemGroup>
  <Warning 
    Condition="'@(Filtered)'!=''"
    Code="CSHTML" 
    File="$(MSBuildProjectDirectory)\%(Filtered.Identity)" 
    Text="View is not set to [BuildAction:Content]"
  />
</Target>

如果看到其他构建操作(例如EmbeddedResource),则可以将它们添加到“过滤的项目”定义中。

如果要进行更高级的检测,则需要实际解析项目文件中适合此Xpath //ItemGroup/*[not(self::Content)]/@Include的任何项目。
<Target Name="EnsureContentOnViewsXML" BeforeTargets="BeforeBuild">
  <XmlPeek XmlInputPath="$(MSBuildProjectFile)" Namespaces="&lt;Namespace Prefix='msb' Uri='schemas.microsoft.com/developer/msbuild/2003'/&gt;"; Query="/msb:Project/msb:ItemGroup/*[not(self::msb:EmbeddedResource)]/@Include">
    <Output TaskParameter="Result" ItemName="AllItems" />
  </XmlPeek>

  <!-- MsBuild uses XPath 1.0 which doesn't have the 'ends-with' or 'matches' function. -->
  <ItemGroup>
    <Filtered Include="@(AllItems)" Condition="'%(Extension)' == '.cshtml'" />
  </ItemGroup>

  <Warning 
    Code="CSHTML" 
    File="$(MSBuildProjectDirectory)\%(Filtered.Identity)" 
    Text="View is not set to [BuildAction:Content]"
    Condition="'@(Filtered)'!=''"
  />
</Target>

除了<Warning ...>,您还可以使用<Error ...>
您需要手动将以下片段之一放入您的项目文件中:

关于razor - 确保将所有* .cshtml文件设置为 “Content”进行构建操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27954267/

相关文章:

c# - microsoft.scripting.hosting.scriptscope 不包含 'SomeFunction' 的定义

c# - 构建失败。有关详细信息,请参阅构建日志

c# - .csproj 程序集的多个提示路径

.net - 跨所有 subview 的 ASP.NET MVC 3 布局 ViewBag 数据

c# - Asp.Net Mvc 5 图像不显示

vb.net - 如何将 Entity Framework 数据模型移动到同一项目中的单独文件夹

c# - 如何同时刷新局部 View 和主视图?

.net - 使用 MSBuild 复制分隔文件列表

c# - 在另一个程序集中找到 Razor Pages

c# - 使用 Razor 模板生成 .aspx 页面