禁用 Razor 仪器

Chr*_*nes 5 asp.net-mvc razor

有没有办法在 Razor 中禁用页面检测?我遇到了一个问题,我试图在 _AppStart 中设置一个 razor 模板委托,然后在其他页面上使用它。它会正常工作,除了检测在 BeginContext/EndContext 中保留对 _AppStart 的引用,这会在其他页面上爆炸。

例如:

// TemplateHolder.cs
public static class TemplateHolder
{
    public static Func<object, object> TheTemplate = null;
}

@* _AppStart.cshtml *@
@{
    TemplateHolder.TheTemplate = @<b>the template</b>;
}

@* OtherPage.cshtml *@
@TemplateHolder.TheTemplate(Model);
Run Code Online (Sandbox Code Playgroud)

在您尝试在 OtherPage.cshtml 中呈现模板之前,一切似乎都可以正常工作,在此之前,您将从内部检测尝试获取 _AppStart 的 HttpContext 时收到错误。

用一点点反射来解决这个问题很容易:

static readonly PropertyInfo _instrumentationService = typeof(WebPageExecutingBase).GetProperty("InstrumentationService", BindingFlags.NonPublic | BindingFlags.Instance);
static readonly PropertyInfo _isAvailableProperty = typeof(InstrumentationService).GetProperty("IsAvailable");

public static void DisableInstrumentation(this WebPageExecutingBase page)
{
    _isAvailableProperty.SetValue(_instrumentationService.GetValue(page), false);
}
Run Code Online (Sandbox Code Playgroud)

... 这可以防止 BeginContext/EndContext 调用被呈现。

但是,Razor 的全部意义不是面向对象和可配置的吗?我觉得我错过了一些东西。