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

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

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


当前回答

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

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

其他回答

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

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符号编译的,所以它可以工作。

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

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

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

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

@if (this.Context.IsDebuggingEnabled)
{
    <button type="button" class="btn btn-warning">Fill file</button>
    <button type="button" class="btn btn-info">Export file</button>
} 

这适用于我的。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配置,你需要:

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

将下面的属性从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
}