Razor中的预处理器指令

我今天正在写我的第一个Razor页面,不知道如何进入

#if debug
...
#else
...
#endif

我如何在Razor中做到这一点?

77822 次浏览

c#和ASP。在视图 . NET MVC中使用#if指令

实际上这个答案是正确的。无论是否通过Model处于调试模式,都必须传递。(或ViewBag),因为所有视图都是在调试模式下编译的。

我刚刚创建了一个扩展方法:

public static bool IsDebug(this HtmlHelper htmlHelper)
{
#if DEBUG
return true;
#else
return false;
#endif
}

然后在我的视图中使用它:

<section id="sidebar">
@Html.Partial("_Connect")
@if (!Html.IsDebug())
{
@Html.Partial("_Ads")
}
<hr />
@RenderSection("Sidebar", required: false)
</section>

因为helper是用DEBUG/RELEASE符号编译的,所以它可以工作。

这是内置到HttpContext:

@if (HttpContext.Current.IsDebuggingEnabled)
{
// Means that debug="true" in Web.config
}

在我看来,这比视图的条件编译更有意义,而且在一些测试场景中很方便。(参见下面的托尼·沃尔的评论。)


边注:NullReferenceException用于HttpContext.Current

Alex Angas提到过,他们得到了一个NullReferenceException与这个解决方案,和一些人已经投票,表明这可能不是一个孤立的事件。

我的最佳猜测是:HttpContext.Current存储在CallContext中,这意味着它只能由处理传入HTTP请求的线程访问。如果你的视图是在不同的线程上呈现的(也许是一些预编译视图的解决方案?),你会得到HttpContext.Currentnull值。

如果你得到这个错误,请在评论中告诉我,并提到如果你正在使用预编译的视图或任何特殊设置,可能导致你的视图被部分呈现/在另一个线程上执行!

默认情况下,MVC视图是不编译的,因此#IF DEBUG不能在视图中工作。如果你想编译视图以访问If DEBUG配置,你需要:

  1. 在Visual Studio中右键单击您的项目
  2. 卸载项目
  3. 编辑项目

将下面的属性从false更改为true

<MvcBuildViews>true</MvcBuildViews>

重新加载项目,然后视图将被编译。

唯一的解决办法就是在你的代码后面加上一个函数

public static Boolean DEBUG(this System.Web.Mvc.WebViewPage page)
{
var value = false;
#if(DEBUG)
value=true;
#endif
return value;
}

然后从视图中调用它:

if(DEBUG())
{
//debug code here
}
else
{
//release code here
}

我知道这不是对问题的直接回答,但因为我非常确定调试配置是实际在本地执行的事实的必然结果,所以你总是可以使用Request.IsLocal属性作为调试之类的测试。因此:

@if (Request.IsLocal)
{
<link rel="stylesheet" type="text/css" href="~/css/compiled/complete.css">
}
else
{
<link rel="stylesheet" type="text/css" href="~/css/compiled/complete.min.css">
}

对我来说,下面的代码运行得非常好。

当应用程序是调试时,我的按钮会出现,当应用程序是释放时,它们不会出现。

@if (this.Context.IsDebuggingEnabled)
{
<button type="button" class="btn btn-warning">Fill file</button>
<button type="button" class="btn btn-info">Export file</button>
}
我的解决办法很愚蠢,但很有效。 在静态文件中定义一个全局常量:

public static class AppConstants
{
#if DEBUG
public const bool IS_DEBUG = true;
#else
public const bool IS_DEBUG = false;
#endif
}

然后在HTML中使用Razor:

@if (AppConstants.IS_DEBUG)
{
<h3>Debug mode</h3>
}
else
{
<h3>Release mode</h3>
}

这适用于我的。net Core 3.0白色标签项目:

@{
#if CORPA
}
<button type="button" class="btn btn-warning">A Button</button>
@{
#else
}
<p>Nothing to see here</p>
@{
#endif
}

在.NET Core中,你可以使用环境标记帮助器来代替检查预处理器变量:

<environment include="Development">
<!--Debug code here-->
</environment>

我需要在<script>标记中工作的类似内容,并发现以下内容对于DOM中的条件标记或条件脚本都很好。

@{
#if NOEXTAUTH
{
@:<!-- A single line block of code -->


<text>
<!--
A multi-line block
-->
</text>
}
#endif
}