Esempio n. 1
0
        /// <summary>
        /// 创建主机生成器
        /// </summary>
        /// <typeparam name="TStartup"></typeparam>
        /// <param name="args"></param>
        /// <returns></returns>
        public IHostBuilder CreateBuilder <TStartup>(string[] args) where TStartup : StartupAbstract
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                         .AddJsonFile("appsettings.json", false)
#if DEBUG
                         .AddJsonFile("appsettings.Development.json", false)
#endif
                         .Build();

            var hostOptions = new HostOptions();

            config.GetSection("Host").Bind(hostOptions);

            if (hostOptions.Urls.IsNull())
            {
                hostOptions.Urls = "http://*:5000";
            }

            return(Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                   .UseDefaultServiceProvider(options => { options.ValidateOnBuild = false; })
                   .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseLogging()
                .UseStartup <TStartup>()
                .UseUrls(hostOptions.Urls);
            }));
        }
Esempio n. 2
0
        /// <summary>
        /// 创建主机生成器
        /// </summary>
        /// <typeparam name="TStartup"></typeparam>
        /// <param name="args"></param>
        /// <returns></returns>
        public IHostBuilder CreateBuilder <TStartup>(string[] args) where TStartup : StartupAbstract
        {
            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                                .AddJsonFile("appsettings.json", false);

            var environmentVariable = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            if (environmentVariable.NotNull())
            {
                configBuilder.AddJsonFile($"appsettings.{environmentVariable}.json", false);
            }

            var config = configBuilder.Build();

            var hostOptions = new HostOptions();

            config.GetSection("Host").Bind(hostOptions);

            if (hostOptions.Urls.IsNull())
            {
                hostOptions.Urls = "http://*:5000";
            }

            return(Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                   .UseDefaultServiceProvider(options => { options.ValidateOnBuild = false; })
                   .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseLogging()
                .UseStartup <TStartup>()
                .UseUrls(hostOptions.Urls);
            }));
        }
        protected StartupAbstract(IHostEnvironment env)
        {
            Env = env;
            var cfgHelper = new ConfigurationHelper();

            //加载主机配置项
            HostOptions = cfgHelper.Get <HostOptions>("Host", env.EnvironmentName) ?? new HostOptions();
        }
        /// <summary>
        /// 启用WebHost
        /// </summary>
        /// <param name="app"></param>
        /// <param name="hostOptions"></param>
        /// <param name="env"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseWebHost(this IApplicationBuilder app, HostOptions hostOptions, IHostEnvironment env)
        {
            //异常处理
            app.UseExceptionHandle();

            //设置默认文档
            var defaultFilesOptions = new DefaultFilesOptions();

            defaultFilesOptions.DefaultFileNames.Clear();
            defaultFilesOptions.DefaultFileNames.Add("index.html");
            app.UseDefaultFiles(defaultFilesOptions);

            app.UseDefaultPage();

            app.UseDocs();

            //反向代理
            if (hostOptions.Proxy)
            {
                app.UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
                });
            }

            //路由
            app.UseRouting();

            //CORS
            app.UseCors("Default");

            //认证
            app.UseAuthentication();

            //授权
            app.UseAuthorization();

            //配置端点
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            //开启Swagger
            if (hostOptions.Swagger || env.IsDevelopment())
            {
                app.UseCustomSwagger();
            }

            //加载模块
            app.UseModules(env);

            //显示启动Logo
            app.ApplicationServices.GetService <IStartLogoProvider>().Show(hostOptions);

            return(app);
        }
Esempio n. 5
0
        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="env"></param>
        /// <param name="cfg"></param>
        protected StartupAbstract(IHostEnvironment env, IConfiguration cfg)
        {
            Env  = env;
            _cfg = cfg;

            //主机配置
            _hostOptions = new HostOptions();
            cfg.GetSection("Host").Bind(_hostOptions);

            if (_hostOptions.Urls.IsNull())
            {
                _hostOptions.Urls = "http://*:5000";
            }
        }
        public static IServiceCollection AddWebHost(this IServiceCollection services, HostOptions hostOptions, IHostEnvironment env)
#endif
        {
            services.AddSingleton(hostOptions);

            services.AddUtils();

            services.AddUtilsMvc();

            //加载模块
            var modules = services.AddModules(env.EnvironmentName, out ModuleCommonOptions moduleCommonOptions);

            //添加对象映射
            services.AddMappers(modules);

            //添加缓存
            services.AddCache(env.EnvironmentName);

            //添加Excel相关功能
            services.AddExcel(env.EnvironmentName, moduleCommonOptions);

            //主动或者开发模式下开启Swagger
            if (hostOptions.Swagger || env.IsDevelopment())
            {
                services.AddSwagger(modules);
            }

            //Jwt身份认证
            services.AddJwtAuth(env.EnvironmentName);

            //添加MVC功能
            services.AddMvc(c =>
            {
                if (hostOptions.Swagger || env.IsDevelopment())
                {
                    //API分组约定
                    c.Conventions.Add(new ApiExplorerGroupConvention());
                }

                //模块中的MVC配置
                foreach (var module in modules)
                {
                    ((ModuleDescriptor)module).Initializer?.ConfigureMvc(c);
                }
            })
#if NETSTANDARD2_0
            .AddJsonOptions(options =>
#elif NETCOREAPP3_1
            .AddNewtonsoftJson(options =>
#endif
            {
                //设置日期格式化格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            })
            .AddValidators(services)//添加验证器
#if NETSTANDARD2_0
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        /// <summary>
        /// 添加WebHost
        /// </summary>
        /// <param name="services"></param>
        /// <param name="hostOptions"></param>
        /// <param name="env">环境</param>
        /// <returns></returns>
#if NETSTANDARD2_0
        public static IServiceCollection AddWebHost(this IServiceCollection services, HostOptions hostOptions, IHostingEnvironment env)
        /// <summary>
        /// 添加WebHost
        /// </summary>
        /// <param name="services"></param>
        /// <param name="hostOptions"></param>
        /// <param name="env">环境</param>
        /// <returns></returns>
        public static IServiceCollection AddWebHost(this IServiceCollection services, HostOptions hostOptions, IHostEnvironment env)
        {
            services.AddSingleton(hostOptions);

            services.AddUtils();

            services.AddUtilsMvc();

            //加载模块
            var modules = services.AddModules();

            //添加对象映射
            services.AddMappers(modules);

            //添加缓存
            services.AddCache(env.EnvironmentName);

            //主动或者开发模式下开启Swagger
            if (hostOptions.Swagger || env.IsDevelopment())
            {
                services.AddSwagger(modules);
            }

            //Jwt身份认证
            services.AddJwtAuth(env.EnvironmentName);

            //添加MVC功能
            services.AddMvc(c =>
            {
                if (hostOptions.Swagger || env.IsDevelopment())
                {
                    //API分组约定
                    c.Conventions.Add(new ApiExplorerGroupConvention());
                }

                //模块中的MVC配置
                foreach (var module in modules)
                {
                    ((ModuleDescriptor)module).Initializer?.ConfigureMvc(c);
                }
            })
            .AddNewtonsoftJson(options =>
            {
                //设置日期格式化格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            })
            .AddValidators(services)//添加验证器
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            //CORS
            services.AddCors(options =>
            {
                /*浏览器的同源策略,就是出于安全考虑,浏览器会限制从脚本发起的跨域HTTP请求(比如异步请求GET, POST, PUT, DELETE, OPTIONS等等,
                 *      所以浏览器会向所请求的服务器发起两次请求,第一次是浏览器使用OPTIONS方法发起一个预检请求,第二次才是真正的异步请求,
                 *      第一次的预检请求获知服务器是否允许该跨域请求:如果允许,才发起第二次真实的请求;如果不允许,则拦截第二次请求。
                 *      Access-Control-Max-Age用来指定本次预检请求的有效期,单位为秒,,在此期间不用发出另一条预检请求。*/
                var preflightMaxAge = hostOptions.PreflightMaxAge < 0 ? new TimeSpan(0, 30, 0) : new TimeSpan(0, 0, hostOptions.PreflightMaxAge);

                options.AddPolicy("Default",
                                  builder => builder.AllowAnyOrigin()
                                  .SetPreflightMaxAge(preflightMaxAge)
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .WithExposedHeaders("Content-Disposition"));//下载文件时,文件名称会保存在headers的Content-Disposition属性里面
            });

            //添加数据库,数据库依赖ILoginInfo,所以需要在添加身份认证以及MVC后添加数据库
            services.AddDb(env.EnvironmentName, modules);

            //解决Multipart body length limit 134217728 exceeded
            services.Configure <FormOptions>(x =>
            {
                x.ValueLengthLimit         = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue;
            });

            //添加HttpClient相关
            services.AddHttpClient();

            //添加模块的自定义服务
            services.AddModuleServices(modules, env);

            //添加模块初始化服务
            services.AddModuleInitializerServices(modules, env);

            //添加模块配置信息
            services.AddModuleOptions();

            //添加Excel相关功能
            services.AddExcel(env.EnvironmentName);

            return(services);
        }
Esempio n. 9
0
        /// <summary>
        /// 启用WebHost
        /// </summary>
        /// <param name="app"></param>
        /// <param name="hostOptions"></param>
        /// <param name="env"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseWebHost(this IApplicationBuilder app, HostOptions hostOptions, IHostEnvironment env)
        {
            //异常处理
            app.UseExceptionHandle();

            //设置默认文档
            var defaultFilesOptions = new DefaultFilesOptions();

            defaultFilesOptions.DefaultFileNames.Clear();
            defaultFilesOptions.DefaultFileNames.Add("index.html");
            app.UseDefaultFiles(defaultFilesOptions);

            //基地址
            var pathBase = hostOptions.PathBase;

            if (pathBase.NotNull())
            {
                pathBase = pathBase.Trim();
                if (!pathBase.StartsWith('/'))
                {
                    pathBase = $"/{pathBase}";
                }

                //1、配置请求基地址:
                app.Use((context, next) =>
                {
                    context.Request.PathBase = pathBase;
                    return(next());
                });

                // 2、配置静态文件基地址:
                app.UsePathBase(pathBase);
            }

            app.UseDefaultPage();

            app.UseDocs();

            //反向代理
            if (hostOptions.Proxy)
            {
                app.UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
                });
            }

            //路由
            app.UseRouting();

            //CORS
            app.UseCors("Default");

            //认证
            app.UseAuthentication();

            //授权
            app.UseAuthorization();

            //配置端点
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            //开启Swagger
            if (hostOptions.Swagger || env.IsDevelopment())
            {
                app.UseCustomSwagger();
            }

            //加载模块
            app.UseModules(env);

            return(app);
        }
Esempio n. 10
0
        public static IApplicationBuilder UseWebHost(this IApplicationBuilder app, HostOptions hostOptions, IHostEnvironment env)
#endif
        {
            //异常处理
            app.UseExceptionHandle();

            //加载模块
            app.UseModules(env);

            //设置默认文档
            var defaultFilesOptions = new DefaultFilesOptions();

            defaultFilesOptions.DefaultFileNames.Clear();
            defaultFilesOptions.DefaultFileNames.Add("index.html");
            app.UseDefaultFiles(defaultFilesOptions);

            app.UseDefaultPage();

            app.UseDocs();

            //反向代理
            if (hostOptions.Proxy)
            {
                app.UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
                });
            }

#if NETCOREAPP3_0
            //路由
            app.UseRouting();
#endif

            //CORS
            app.UseCors("Default");

            //认证
            app.UseAuthentication();

#if NETCOREAPP3_0
            //授权
            app.UseAuthorization();

            //配置端点
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
#endif

            //开启Swagger
            if (hostOptions.Swagger || env.IsDevelopment())
            {
                app.UseCustomSwagger();
            }

#if NETSTANDARD2_0
            app.UseMvc();
#endif

            return(app);
        }
Esempio n. 11
0
        /// <summary>
        /// 启用WebHost
        /// </summary>
        /// <param name="app"></param>
        /// <param name="hostOptions"></param>
        /// <param name="env"></param>
        /// <returns></returns>
#if NETSTANDARD2_0
        public static IApplicationBuilder UseWebHost(this IApplicationBuilder app, HostOptions hostOptions, Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
Esempio n. 12
0
        /// <summary>
        /// 启用默认页
        /// </summary>
        /// <param name="app"></param>
        /// <param name="hostOptions"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseDefaultPage(this IApplicationBuilder app, HostOptions hostOptions)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/app");

            if (Directory.Exists(path))
            {
                var options = new StaticFileOptions
                {
                    FileProvider = new PhysicalFileProvider(path),
                    RequestPath  = new PathString("/app")
                };

                app.UseStaticFiles(options);

                var appPath        = hostOptions?.BaseUrl?.Trim('/').IsNull() == false ? $"{hostOptions.BaseUrl.Trim('/')}/app" : "app";
                var rewriteOptions = new RewriteOptions().AddRedirect("^$", appPath);

                app.UseRewriter(rewriteOptions);
            }

            return(app);
        }
Esempio n. 13
0
        /// <summary>
        /// 添加WebHost
        /// </summary>
        /// <param name="services"></param>
        /// <param name="hostOptions"></param>
        /// <param name="env">环境</param>
        /// <param name="cfg"></param>
        /// <returns></returns>
        public static IServiceCollection AddWebHost(this IServiceCollection services, HostOptions hostOptions, IHostEnvironment env, IConfiguration cfg)
        {
            services.AddSingleton(hostOptions);

            services.AddNetModularServices();

            //CORS
            services.AddCors(options =>
            {
                /*浏览器的同源策略,就是出于安全考虑,浏览器会限制从脚本发起的跨域HTTP请求(比如异步请求GET, POST, PUT, DELETE, OPTIONS等等,
                 *      所以浏览器会向所请求的服务器发起两次请求,第一次是浏览器使用OPTIONS方法发起一个预检请求,第二次才是真正的异步请求,
                 *      第一次的预检请求获知服务器是否允许该跨域请求:如果允许,才发起第二次真实的请求;如果不允许,则拦截第二次请求。
                 *      Access-Control-Max-Age用来指定本次预检请求的有效期,单位为秒,,在此期间不用发出另一条预检请求。*/
                var preflightMaxAge = hostOptions.PreflightMaxAge < 0 ? new TimeSpan(0, 30, 0) : new TimeSpan(0, 0, hostOptions.PreflightMaxAge);

                options.AddPolicy("Default",
                                  builder => builder.AllowAnyOrigin()
                                  .SetPreflightMaxAge(preflightMaxAge)
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .WithExposedHeaders("Content-Disposition"));//下载文件时,文件名称会保存在headers的Content-Disposition属性里面
            });


            //解决Multipart body length limit 134217728 exceeded
            services.Configure <FormOptions>(x =>
            {
                x.ValueLengthLimit         = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue;
            });

            //添加HttpClient相关
            services.AddHttpClient();

            //添加OSS相关功能
            services.AddOSS(cfg);

            //添加默认启动Logo
            services.AddSingleton <IStartLogoProvider, DefaultStartLogoProvider>();

            return(services);
        }
Esempio n. 14
0
        /// <summary>
        /// 添加WebHost
        /// </summary>
        /// <param name="services"></param>
        /// <param name="hostOptions"></param>
        /// <param name="env">环境</param>
        /// <returns></returns>
        public static IServiceCollection AddWebHost(this IServiceCollection services, HostOptions hostOptions, IHostEnvironment env)
        {
            services.AddSingleton(hostOptions);

            services.AddUtils();

            services.AddUtilsMvc();

            //加载模块
            var modules = services.AddModules(env.EnvironmentName);

            //添加对象映射
            services.AddMappers(modules);

            //添加缓存
            services.AddCache(env.EnvironmentName);

            //主动或者开发模式下开启Swagger
            if (hostOptions.Swagger || env.IsDevelopment())
            {
                services.AddSwagger(modules);
            }

            //Jwt身份认证
            services.AddJwtAuth(env.EnvironmentName);

            //添加MVC功能
            services.AddMvc(c =>
            {
                if (hostOptions.Swagger || env.IsDevelopment())
                {
                    //API分组约定
                    c.Conventions.Add(new ApiExplorerGroupConvention());
                }

                //模块中的MVC配置
                foreach (var module in modules)
                {
                    ((ModuleDescriptor)module).Initializer?.ConfigureMvc(c);
                }
            })
            .AddNewtonsoftJson(options =>
            {
                //设置日期格式化格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            })
            .AddValidators(services)//添加验证器
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            //CORS
            services.AddCors(options =>
            {
                options.AddPolicy("Default",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .WithExposedHeaders("Content-Disposition"));//下载文件时,文件名称会保存在headers的Content-Disposition属性里面
            });

            //添加数据库,数据库依赖ILoginInfo,所以需要在添加身份认证以及MVC后添加数据库
            services.AddDb(env.EnvironmentName, modules);

            //解决Multipart body length limit 134217728 exceeded
            services.Configure <FormOptions>(x =>
            {
                x.ValueLengthLimit         = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue;
            });

            //添加HttpClient相关
            services.AddHttpClient();

            //添加模块的自定义服务
            services.AddModuleServices(modules);

            return(services);
        }
        /// <summary>
        /// 启用WebHost
        /// </summary>
        /// <param name="app"></param>
        /// <param name="hostOptions"></param>
        /// <param name="env"></param>
        /// <returns></returns>
#if NETSTANDARD2_0
        public static IApplicationBuilder UseWebHost(this IApplicationBuilder app, HostOptions hostOptions, IHostingEnvironment env)