我设法写了一些能够正确转换链接的东西。
大纲是:
在帮助控制器的构造函数创建在CREF发现字符串之间一个新的懒惰的IDictionary映射(例如,M:Api.Method.Description(System.String)和相关ApiDescription
。
_methodReferences = new Lazy<IDictionary<string, ApiDescription>>(() => {
var dictionary = new Dictionary<string, ApiDescription>();
var apiExplorer = new ApiExplorer(config);
foreach (var apiDescription in apiExplorer.ApiDescriptions)
{
var descriptor = apiDescription.ActionDescriptor as ReflectedHttpActionDescriptor;
if (descriptor != null)
{
var methodName = string.Format(
@"M:{0}.{1}({2})",
descriptor.MethodInfo.DeclaringType.FullName,
descriptor.MethodInfo.Name,
string.Join(@",",descriptor.GetParameters().Select(x => x.ParameterType.FullName))
);
dictionary[methodName] = apiDescription;
}
}
return dictionary;
});
通过这个懒到书页的各种模型(你可能需要创建额外的型号)我已经给了他们所有的基类用下面的代码:
public abstract class HelpPageModelBase
{
private static Regex _seeRegex = new Regex("<see cref=\"([^\"]+)\" />");
private readonly Lazy<IDictionary<string, ApiDescription>> _methodReferences;
protected HelpPageModelBase(Lazy<IDictionary<string, ApiDescription>> methodReferences)
{
_methodReferences = methodReferences;
}
protected HelpPageModelBase(HelpPageModelBase parent)
{
_methodReferences = parent._methodReferences;
}
public string ParseDoc(string documentation, UrlHelper url)
{
if (documentation == null)
{
return null;
}
return _seeRegex.Replace(documentation,
match => {
if (_methodReferences.Value.ContainsKey(match.Groups[1].Value))
{
var descriptor = _methodReferences.Value[match.Groups[1].Value];
return string.Format(@"<a href='{0}'>{1} {2}</a>",
url.Action("Api",
"Help",
new {
apiId = descriptor.GetFriendlyId()
}),
descriptor.HttpMethod.Method,
descriptor.RelativePath
);
}
return "";
});
}
}
任何地方在有api.Documentation.Trim()
的观点 - 或者Html.Raw(api.Documentation)
如果你已经按照Web Api Help Page- don't escape html in xml documentation - 你现在包装,使其成为
@Html.Raw(Model.ParseDoc(api.Documentation, Url))
你会发现,要做到这一点,你需要做的各种ModelDescriptions从HelpPageModelBase继承 - 并将父API模型传递给它们(如果更容易,则传递给Lazy),但它最终还是有效的。
我对这个解决方案并不满意,你可能会发现使用默认的Http配置生成Lazy的一些静态ParseDoc方法更容易(但是由于我做的其他扩展对我的情况不起作用)。如果你看到更好的方式,请分享!希望它给你一个起点。