[英]Preprocessor directives in Razor
我今天正在写我的第一个 Razor 页面,不知道如何进入
#if debug
...
#else
...
#endif
如何在 Razor 中做到这一点?
我刚刚创建了一个扩展方法:
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>
由于帮助程序是使用 DEBUG/RELEASE 符号编译的,因此它可以工作。
这是内置于HttpContext
:
@if (HttpContext.Current.IsDebuggingEnabled)
{
// Means that debug="true" in Web.config
}
IMO,这比视图的条件编译更有意义,并且在某些测试场景中派上用场。 (请参阅下面的托尼·沃尔( Tony Wall)评论。)
HttpContext.Current
NullReferenceException
Alex Angas 提到他们通过这个解决方案得到了一个NullReferenceException
,并且有一些人表示这可能不是一个孤立的事件。
我最好的猜测是: HttpContext.Current
存储在CallContext
,这意味着它只能由处理传入 HTTP 请求的线程访问。 如果您的视图在不同的线程上呈现(也许是预编译视图的一些解决方案?),您将获得HttpContext.Current
的null
值。
如果您收到此错误,请在评论中告诉我并提及您是否使用预编译视图或任何可能导致您的视图在另一个线程上部分呈现/执行的特殊设置!
C# 和 ASP.NET MVC:在视图中使用 #if 指令
其实这个答案有正确的答案。 无论您是否处于调试模式,您都必须通过模型传递。 (或 ViewBag),因为所有视图都是在调试模式下编译的。
我知道这不是问题的直接答案,但由于我很确定调试配置是您实际在本地执行的必然结果,因此您始终可以将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">
}
我的解决方案非常愚蠢,但它有效。 在静态文件中的某处定义一个全局常量:
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 中,您可以使用环境标记助手而不是检查预处理器变量:
<environment include="Development">
<!--Debug code here-->
</environment>
这在 .NET Core 3.0 白标项目中对我有用:
@{
#if CORPA
}
<button type="button" class="btn btn-warning">A Button</button>
@{
#else
}
<p>Nothing to see here</p>
@{
#endif
}
默认情况下,不会编译 MVC 视图,因此 #IF DEBUG 无法在视图中工作。 如果要编译视图以访问 IF DEBUG 配置,则需要:
将以下属性从 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
}
对我来说,下面的代码效果很好。
当应用程序正在调试我的按钮时会出现,当是Release 时,它们不会出现。
@if (this.Context.IsDebuggingEnabled)
{
<button type="button" class="btn btn-warning">Fill file</button>
<button type="button" class="btn btn-info">Export file</button>
}
我需要一些类似的东西也可以在<script>
标签中使用,并且发现以下内容适用于 DOM 中的条件标记或条件脚本。
@{
#if NOEXTAUTH
{
@:<!-- A single line block of code -->
<text>
<!--
A multi-line block
-->
</text>
}
#endif
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.