Problem
I’m working on my first Razor page today, and I’m having trouble figuring out how to enter it.
#if debug
...
#else
...
#endif
How can I accomplish this in Razor?
Asked by mamu
Solution #1
I’ve just built a new mechanism for adding extensions:
public static bool IsDebug(this HtmlHelper htmlHelper)
{
#if DEBUG
return true;
#else
return false;
#endif
}
Then I utilized it in my arguments as follows:
<section id="sidebar">
@Html.Partial("_Connect")
@if (!Html.IsDebug())
{
@Html.Partial("_Ads")
}
<hr />
@RenderSection("Sidebar", required: false)
</section>
It works because the helper is compiled with the DEBUG/RELEASE symbol.
Answered by Shawn Wildermuth
Solution #2
HttpContext already has this:
@if (HttpContext.Current.IsDebuggingEnabled)
{
// Means that debug="true" in Web.config
}
This, in my opinion, makes more sense for views than conditional compilation and is useful in some testing cases. (For more on this, see Tony Wall’s comment below.)
Alex Angas remarked that this solution causes a NullReferenceException, and a few people have upvoted, showing that this isn’t an unique incident.
HttpContext is my best estimate. Current is saved in CallContext, which means it can only be accessed by the thread handling the incoming HTTP request. You’ll obtain a null value for HttpContext if your views are rendered on a different thread (maybe any alternatives for precompiled views?). Current.
If you receive this error, please let me know in the comments and let me know if you’re using precompiled views or anything else that would cause your views to be rendered/executed partially on another thread!
Answered by Jordan Gray
Solution #3
Using the #if directive in a view in C# and ASP.NET MVC
That is, in fact, the correct response. Because all views are compiled in debug mode, you’ll need to pass whether you’re in debug mode via the Model. (or ViewBag).
Answered by Buildstarted
Solution #4
Instead of testing the preprocessor variables in.NET Core, you can use the environment tag helper:
<environment include="Development">
<!--Debug code here-->
</environment>
Answered by beleester
Solution #5
You can always use the Request.IsLocal attribute as a debug like test because I’m very sure debug configuration is correlative to the fact that you’re actually executing locally. As an example:
@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">
}
Answered by Sbu
Post is based on https://stackoverflow.com/questions/4696175/preprocessor-directives-in-razor