WebAPI HelpPage支持Area

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[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:

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);
        }
    }

 

posted @ 2018-09-25 17:14  小小渔  阅读(767)  评论(0编辑  收藏  举报