好吧,我从来没有忘记想要这个,并且一直希望有一天我能解决它,谢天谢地我做到了。
我已经覆盖了默认的 WebViewPage(我使用 Razor 引擎),特别是 ExecutePageHierarchy 来注入评论:
public abstract class PaladinWebViewPage : PaladinWebViewPage<dynamic>
{
}
public abstract class PaladinWebViewPage<TModel> : WebViewPage<TModel>
{
public bool DisplaySourceCodeComments
{
get { return ((bool?) ViewBag.__DisplaySourceCodeComments) ?? false; }
set { ViewBag.__DisplaySourceCodeComments = value; }
}
public override void ExecutePageHierarchy()
{
base.ExecutePageHierarchy();
// Filters can be used to set and clear this value so we can decide when to show this comment
if (!DisplaySourceCodeComments) return;
var sw = Output as StringWriter;
if (sw == null) return;
var sb = sw.GetStringBuilder();
sb.Insert(0, string.Format("<!-- Start of {0} -->", VirtualPath));
sb.AppendFormat("<!-- End of {0} -->", VirtualPath);
}
VirtualPath 告诉我们用于构建 HTML 的确切文件,因此我们可以在之前和之后注入文件名。这目前没有做任何事情,因为默认设置是不显示评论(DisplaySourceCodeComments 中的“?? false”)。
此外,要使用此视图页面,您需要编辑 Views/Web.config 并将 pageBaseType 更改为此类型。
我想有选择地打开和关闭这些评论,所以我创建了一个 ActionFilter:
public class DisplaySourceCodeCommentsAttribute : ActionFilterAttribute
{
private readonly bool _displaceSourceCodeComments;
public DisplaySourceCodeCommentsAttribute(bool displaceSourceCodeComments)
{
_displaceSourceCodeComments = displaceSourceCodeComments;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var viewResult = filterContext.Result as ViewResultBase;
if (viewResult == null) return;
viewResult.ViewBag.__DisplaySourceCodeComments = _displaceSourceCodeComments;
}
}
我有点不高兴我不得不在这里使用 ViewBag 并在视图页面覆盖中单独使用,因为它们没有紧密链接,但我找不到过滤器直接与视图页面交互的方法,所以这是一个必要的软糖。它确实有一个好处,即显示视图或部分的源代码也会自动为任何子部分显示它,直到您再次将其关闭,因为 ViewBag 是沿着链传递的。
有了这个,任何操作都可以使用 [DisplaySourceCodeComments(true)] 打开源代码注释
或者,显然用 false 再次关闭它
Attribute 检查上下文结果是否为 ViewResultBase,这意味着只有 Views 和 Partials,因此 Json 或 Content 或重定向不受影响,这也非常方便。
最后,我在调试模式下运行时将此操作过滤器设为全局,以便每个视图和部分视图都包含源注释,方法是在 global.asax.cs 中添加以下行:
[#]如果调试
// When in debug mode include HTML comments showing where a view or partial has come from
GlobalFilters.Filters.Add(new DisplaySourceCodeCommentsAttribute(true));
[#]万一
我真的很高兴我终于把它整理好了,所以我希望这对其他人有用。