WebAPI原生的HelpPage文檔並不支持Area的生成,需進行以下改造:api
WebApiConfig:ui
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:this
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[0]; string queryKeyString = null; if (urlParts.Length > 1) { string query = urlParts[1]; 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[1].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:url
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); } }