WebAPI原生的HelpPage文档并不支持Area的生成,需进行如下改造:

WebApiConfig:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务 // Web API 路由
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{area}/{controller}/{action}",
defaults: new { id = RouteParameter.Optional }
); //移除XML输出格式
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}

Areas.HelpPage.ApiDescriptionExtensions:

public static class ApiDescriptionExtensions
{
/// <summary>
/// Generates an URI-friendly ID for the <see cref="ApiDescription"/>. E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}"
/// </summary>
/// <param name="description">The <see cref="ApiDescription"/>.</param>
/// <returns>The ID as a string.</returns>
public static string GetFriendlyId(this ApiDescription description)
{
GetAreaName(description); //获取区域名称 string path = description.RelativePath;
string[] urlParts = path.Split('?');
string localPath = urlParts[];
string queryKeyString = null;
if (urlParts.Length > )
{
string query = urlParts[];
string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys;
queryKeyString = String.Join("_", queryKeys);
} StringBuilder friendlyPath = new StringBuilder();
friendlyPath.AppendFormat("{0}-{1}",
description.HttpMethod.Method,
localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty));
if (queryKeyString != null)
{
friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-'));
}
return friendlyPath.ToString();
} /// <summary>
/// 获取区域名称
/// </summary>
/// <param name="description"></param>
private static void GetAreaName(this ApiDescription description)
{
//获取controller的fullname
string controllerFullName = description.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
//匹配areaName
string areaName = Regex.Match(controllerFullName, @"Area.([^,]+)\.C").Groups[].ToString().Replace(".", "");
if (string.IsNullOrEmpty(areaName))
{
//若不是areas下的controller,将路由格式中的{area}去掉
description.RelativePath = description.RelativePath.Replace("{area}/", "");
}
else
{
//若是areas下的controller,将路由格式中的{area}替换为真实areaname
description.RelativePath = description.RelativePath.Replace("{area}", areaName);
}
}
}

Areas.HelpPage.Controllers.HelpController:

public class HelpController : Controller
{
private const string ErrorViewName = "Error"; public HelpController()
: this(GlobalConfiguration.Configuration)
{
} public ActionResult Api(string apiId)
{
if (!String.IsNullOrEmpty(apiId))
{
HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);
if (apiModel != null)
{
//防止生成帮助文档时将area作为了Uri参数
foreach (var item in apiModel.UriParameters)
{
if (item.Name.ToLower().Equals("area"))
{
apiModel.UriParameters.Remove(item);
break;
}
}
return View(apiModel);
}
} return View(ErrorViewName);
}
}
04-24 19:30