mam*_*amu 223 asp.net-mvc preprocessor razor
我今天正在写我的第一个剃刀页面,无法弄清楚如何进入 #if debug #else #endif
如何在剃刀中输入预处理器?
Sha*_*uth 363
我刚刚创建了一个扩展方法:
public static bool IsDebug(this HtmlHelper htmlHelper)
{
#if DEBUG
return true;
#else
return false;
#endif
}
Run Code Online (Sandbox Code Playgroud)
然后在我的视图中使用它,如下所示:
<section id="sidebar">
@Html.Partial("_Connect")
@if (!Html.IsDebug())
{
@Html.Partial("_Ads")
}
<hr />
@RenderSection("Sidebar", required: false)
</section>
Run Code Online (Sandbox Code Playgroud)
由于帮助程序是使用DEBUG/RELEASE符号编译的,因此可以正常工作.
Jor*_*ray 293
@if (HttpContext.Current.IsDebuggingEnabled)
{
// Means that debug="true" in Web.config
}
Run Code Online (Sandbox Code Playgroud)
IMO,这比视图的条件编译更有意义,并且在某些测试场景中派上用场.(参见下面的Code Chief的评论.)
NullReferenceExceptionforHttpContext.Current亚历克斯安加斯提到他们得到了NullReferenceException这个解决方案,并且有一些人已经投票表明这可能不是一个孤立的事件.
我最好的猜测:HttpContext.Current存储在CallContext,意味着它只能由处理传入HTTP请求的线程访问.如果您的视图是在不同的线程上呈现的(也许是预编译视图的一些解决方案?),您将获得一个null值HttpContext.Current.
如果您收到此错误,请在评论中告诉我并提及您是否使用预编译视图或任何特殊设置,这可能导致您的视图在另一个线程上被部分呈现/执行!
Bui*_*ted 23
实际上答案是正确的答案.无论你是否通过模型进入调试模式,你都必须通过.(或ViewBag)因为所有视图都是在调试模式下编译的.
Sim*_*din 14
我知道这不是问题的直接答案,但由于我非常确定调试配置是您实际在本地执行的必然结果,因此您始终可以将该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">
}
Run Code Online (Sandbox Code Playgroud)
ted*_*bus 13
我的解决方案非常愚蠢,但它有效。在静态文件中的某处定义一个全局常量:
public static class AppConstants
{
#if DEBUG
public const bool IS_DEBUG = true;
#else
public const bool IS_DEBUG = false;
#endif
}
Run Code Online (Sandbox Code Playgroud)
然后在 HTML 中将它与 Razor 一起使用:
@if (AppConstants.IS_DEBUG)
{
<h3>Debug mode</h3>
}
else
{
<h3>Release mode</h3>
}
Run Code Online (Sandbox Code Playgroud)
小智 11
在 .NET Core 中,您可以使用环境标记助手而不是检查预处理器变量:
<environment include="Development">
<!--Debug code here-->
</environment>
Run Code Online (Sandbox Code Playgroud)
这在 .NET Core 3.0 白标项目中对我有用:
@{
#if CORPA
}
<button type="button" class="btn btn-warning">A Button</button>
@{
#else
}
<p>Nothing to see here</p>
@{
#endif
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,不会编译MVC视图,因此#IF DEBUG无法在视图中工作。如果要编译视图以访问IF DEBUG配置,则需要:
将以下属性从false更改为true
<MvcBuildViews>true</MvcBuildViews>
Run Code Online (Sandbox Code Playgroud)
重新加载您的项目,然后将要编译视图。
唯一的其他解决方法是在代码中包含一个函数
public static Boolean DEBUG(this System.Web.Mvc.WebViewPage page)
{
var value = false;
#if(DEBUG)
value=true;
#endif
return value;
}
Run Code Online (Sandbox Code Playgroud)
然后从视图调用它:
if(DEBUG())
{
//debug code here
}
else
{
//release code here
}
Run Code Online (Sandbox Code Playgroud)
小智 5
对我来说,下面的代码非常有效。
当应用程序正在调试时,我的按钮出现,而当发布时,它们不会出现。
@if (this.Context.IsDebuggingEnabled)
{
<button type="button" class="btn btn-warning">Fill file</button>
<button type="button" class="btn btn-info">Export file</button>
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62675 次 |
| 最近记录: |