侧边栏壁纸
博主头像
分享你我博主等级

行动起来,活在当下

  • 累计撰写 107 篇文章
  • 累计创建 13 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

.net core给所有api接口加统一前缀

管理员
2020-09-28 / 0 评论 / 0 点赞 / 5 阅读 / 6501 字
    /// <summary>
    /// 版本控制
    /// </summary>
    public static class MvcOptionsExtensions
    {
        public static void UseGeneralRoutePrefix(this MvcOptions opts, IRouteTemplateProvider routeAttribute)
        {
            // 添加我们自定义 实现IApplicationModelConvention的RoutePrefixConvention
            opts.Conventions.Add(new RoutePrefixConvention(routeAttribute));
        }
        public static void UseGeneralRoutePrefix(this MvcOptions opts, string prefix)
        {
            // 添加我们自定义 实现IApplicationModelConvention的RouteAttribute
            opts.UseGeneralRoutePrefix(new RouteAttribute(prefix));
        }
    }
    /// <summary>
    /// 全局路由前缀配置
    /// </summary>
    public class RoutePrefixConvention : IApplicationModelConvention
    {
        /// <summary>
        /// 定义一个路由前缀变量
        /// </summary>
        private readonly AttributeRouteModel _routePrefix;
        /// <summary>
        /// 调用时传入指定的路由前缀
        /// </summary>
        /// <param name="route"></param>
        public RoutePrefixConvention(IRouteTemplateProvider route)
        {
            _routePrefix = new AttributeRouteModel(route);
        }
        /// <summary>
        /// 接口的Apply方法
        /// </summary>
        /// <param name="application"></param>
        public void Apply(ApplicationModel application)
        {
            //遍历所有的 Controller
            foreach (var selector in application.Controllers.SelectMany(c => c.Selectors))
            {
                if (selector.AttributeRouteModel != null)
                {
                    selector.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(_routePrefix, selector.AttributeRouteModel);
                }
                else
                {
                    selector.AttributeRouteModel = _routePrefix;
                }
            }
        }
    }


在Startup文件中配置

        public void ConfigureServices(IServiceCollection services)
        {
            //#region WkHtmlWrapper
            //services.UseWkHtmlConverter();
            //#endregion
            //注配置文件appsettings.json
            services.AddSingleton(new ConfigExtensions(Env.ContentRootPath));
            #region 所有控制器添加前缀
            //MVC service registration
            //https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#mvc-service-registration
            services.AddControllersWithViews(o => { o.UseGeneralRoutePrefix("api/v{version:apiVersion}"); });
            services.AddApiVersioning(o => o.ReportApiVersions = true);
            #endregion
          }



0

评论区