Example #1
0
        public static IServiceCollection ConfigureMvcRazorPages(this IServiceCollection services,
                                                                CompatibilityVersion version, string startPageUrl = "", string startPageArea = "")
        {
            services.AddMvc()
            .SetCompatibilityVersion(version)
            .AddRazorPagesOptions(options =>
            {
                var isSupportAreas = !string.IsNullOrWhiteSpace(startPageArea);
                if (isSupportAreas)
                {
                    options.Conventions.AddAreaPageRoute(startPageArea, startPageUrl, string.Empty);
                }
                else if (!string.IsNullOrWhiteSpace(startPageUrl))
                {
                    options.Conventions.AddPageRoute(startPageUrl, string.Empty);
                }
            })
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.Add(new SitemapRouteConvention());
            })
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AddPageRoute("/Sitemap", "sitemap.xml");
            });

            return(services);
        }
Example #2
0
        public static IMvcBuilder SetCompatibilityVersion(this IMvcBuilder builder, CompatibilityVersion version)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            builder.Services.Configure <MvcCompatibilityOptions>(o => o.CompatibilityVersion = version);
            return(builder);
        }
        /// <summary>
        /// Adds the minimum essential MVC services to the DI container for web API services.
        /// (MVC Core, JSON Formatters, CORS, API Explorer, Authorization)
        /// Additional services must be added separately using the <see cref="IMvcCoreBuilder"/> returned from this method.
        /// </summary>
        /// <param name="services">MVC Core builder.</param>
        /// <param name="compatibilityVersion">Compatibility version for MVC.</param>
        public static IMvcCoreBuilder AddWebApi(this IServiceCollection services, CompatibilityVersion compatibilityVersion)
        {
            IMvcCoreBuilder builder = services.AddMvcCore().SetCompatibilityVersion(compatibilityVersion);

            return(builder.AddFormatterMappings()
                   .AddJsonFormatters()
                   .AddCors()
                   .AddApiExplorer()
                   .AddAuthorization());
        }
Example #4
0
    private static ConfigureCompatibilityOptions <TestOptions> Create(
        CompatibilityVersion version,
        IReadOnlyDictionary <string, object> defaultValues)
    {
        var compatibilityOptions = Options.Create(new MvcCompatibilityOptions()
        {
            CompatibilityVersion = version
        });

        return(new TestConfigure(NullLoggerFactory.Instance, compatibilityOptions, defaultValues));
    }
Example #5
0
        private static RazorViewEngineOptionsSetup GetSetup(
            CompatibilityVersion compatibilityVersion = CompatibilityVersion.Latest,
            IHostingEnvironment hostingEnvironment    = null)
        {
            hostingEnvironment = hostingEnvironment ?? Mock.Of <IHostingEnvironment>();
            var compatibilityOptions = new MvcCompatibilityOptions {
                CompatibilityVersion = compatibilityVersion
            };

            return(new RazorViewEngineOptionsSetup(
                       hostingEnvironment,
                       NullLoggerFactory.Instance,
                       Options.Options.Create(compatibilityOptions)));
        }
Example #6
0
        public static void ConfigureMvcApi(this IServiceCollection services, CompatibilityVersion version)
        {
            services.AddMvc()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver      = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            })
            .SetCompatibilityVersion(version);

            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                    var errorResponse = new ApiError(context.ModelState);
                    return(new BadRequestObjectResult(errorResponse));
                };
            });

            services.AddResponseCaching();
        }
Example #7
0
        public static void AddScfServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env, CompatibilityVersion compatibilityVersion)
        {
            //如果运行在IIS中,需要添加IIS配置
            //https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/iis/index?view=aspnetcore-2.1&tabs=aspnetcore2x#supported-operating-systems
            //services.Configure<IISOptions>(options =>
            //{
            //    options.ForwardClientCertificate = false;
            //});


            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            //services.AddMvc(options =>
            //{
            //    //options.Filters.Add<HttpGlobalExceptionFilter>();
            //})
            //.SetCompatibilityVersion(compatibilityVersion)
            //.AddRazorPagesOptions(options =>
            //{
            //    //options.AllowAreas = true;//支持 Area
            //    //options.AllowMappingHeadRequestsToGetHandler = false;//https://www.learnrazorpages.com/razor-pages/handler-methods
            //})


            var builder = services.AddRazorPages()
                          .AddScfAreas()//注册所有 Scf 的 Area 模块(必须)
                          .AddXmlSerializerFormatters()
                          .AddJsonOptions(options =>
            {
                //忽略循环引用
                //options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                //options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            })
                          //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1&tabs=aspnetcore2x
                          //.AddSessionStateTempDataProvider()
                          //忽略JSON序列化过程中的循环引用:https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
                          .AddRazorPagesOptions(options =>
            {
                //自动注册  防止跨站请求伪造(XSRF/CSRF)攻击
                options.Conventions.Add(new Core.Conventions.AutoValidateAntiForgeryTokenModelConvention());
            });

            ;


#if DEBUG
            //Razor启用运行时编译,多个项目不需要手动编译。
            if (env.IsDevelopment())
            {
                builder.AddRazorRuntimeCompilation(options =>
                {
                    var libraryPath = Path.GetFullPath(Path.Combine(env.ContentRootPath, "..", "Senparc.Areas.Admin"));
                    options.FileProviders.Add(new PhysicalFileProvider(libraryPath));
                });
            }
#endif


            //services.AddSenparcGlobalServices(configuration);//Senparc.CO2NET 全局注册    //已经在startup.cs中注册

            //支持 AutoMapper
            services.AddAutoMapper(_ => _.AddProfile <Core.AutoMapProfile.AutoMapperConfigs>());

            //支持 Session
            services.AddSession();
            //解决中文进行编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            //使用内存缓存
            services.AddMemoryCache();

            //注册 SignalR
            services.AddSignalR();
            //注册 Lazy<T>
            services.AddTransient(typeof(Lazy <>));

            services.Configure <SenparcCoreSetting>(configuration.GetSection("SenparcCoreSetting"))
            .AddSenparcEntitiesDI();     //SQL Server设置

            //自动依赖注入扫描
            services.ScanAssamblesForAutoDI();
            //已经添加完所有程序集自动扫描的委托,立即执行扫描(必须)
            AssembleScanHelper.RunScan();
            //services.AddSingleton<Core.Cache.RedisProvider.IRedisProvider, Core.Cache.RedisProvider.StackExchangeRedisProvider>();

            //注册 User 登录策略
            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserAnonymous", policy =>
                {
                    policy.RequireClaim("UserMember");
                });
            });
            services.AddHttpContextAccessor();
            services.AddScoped(typeof(Areas.Admin.Filters.AuthenticationResultFilterAttribute));
            services.AddScoped(typeof(Areas.Admin.Filters.AuthenticationAsyncPageFilterAttribute));
            services.AddScoped(typeof(ISqlClientFinanceData), typeof(SqlClientFinanceData));
            services.AddScoped(typeof(ISqlBaseFinanceData), typeof(SqlClientFinanceData));
            services.AddScoped(typeof(Senparc.Scf.Repository.IRepositoryBase <>), typeof(Senparc.Scf.Repository.RepositoryBase <>));
            services.AddScoped(typeof(ISysButtonRespository), typeof(SysButtonRespository));
            services.AddScoped(typeof(Core.WorkContext.Provider.IAdminWorkContextProvider), typeof(Core.WorkContext.Provider.AdminWorkContextProvider));
            services.AddTransient <Microsoft.AspNetCore.Mvc.Infrastructure.IActionContextAccessor, Microsoft.AspNetCore.Mvc.Infrastructure.ActionContextAccessor>();

            //激活 Xscf 扩展引擎
            services.StartEngine();
        }
Example #8
0
        public static void AddScfServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env, CompatibilityVersion compatibilityVersion)
        {
            //如果运行在IIS中,需要添加IIS配置
            //https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/iis/index?view=aspnetcore-2.1&tabs=aspnetcore2x#supported-operating-systems
            //services.Configure<IISOptions>(options =>
            //{
            //    options.ForwardClientCertificate = false;
            //});

            //启用以下代码强制使用 https 访问
            //services.AddHttpsRedirection(options =>
            //{
            //    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
            //    options.HttpsPort = 443;
            //});

            //读取Log配置文件
            var repository = LogManager.CreateRepository("NETCoreRepository");

            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));

            //提供网站根目录
            if (env.ContentRootPath != null)
            {
                SiteConfig.ApplicationPath = env.ContentRootPath;
                SiteConfig.WebRootPath     = env.WebRootPath;
            }

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //services.AddMvc(options =>
            //{
            //    //options.Filters.Add<HttpGlobalExceptionFilter>();
            //})
            //.SetCompatibilityVersion(compatibilityVersion)
            //.AddRazorPagesOptions(options =>
            //{
            //    //options.AllowAreas = true;//支持 Area
            //    //options.AllowMappingHeadRequestsToGetHandler = false;//https://www.learnrazorpages.com/razor-pages/handler-methods
            //})

            services.AddSenparcGlobalServices(configuration);

            var builder = services.AddRazorPages(opt =>
            {
                //opt.RootDirectory = "/";
            })
                          .AddScfAreas(env)//注册所有 Scf 的 Area 模块(必须)
                          .AddXmlSerializerFormatters()
                          .AddJsonOptions(options =>
            {
                //忽略循环引用
                //options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                //options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            })
                          //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1&tabs=aspnetcore2x
                          //.AddSessionStateTempDataProvider()
                          //忽略JSON序列化过程中的循环引用:https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
                          .AddRazorPagesOptions(options =>
            {
                //自动注册  防止跨站请求伪造(XSRF/CSRF)攻击
                options.Conventions.Add(new Core.Conventions.AutoValidateAntiForgeryTokenModelConvention());
            });

            ;

#if DEBUG
            //Razor启用运行时编译,多个项目不需要手动编译。
            if (env.IsDevelopment())
            {
                builder.AddRazorRuntimeCompilation(options =>
                {
                    //自动索引所有需要使用 RazorRuntimeCompilation 的模块
                    foreach (var razorRegister in Senparc.Scf.XscfBase.Register.RegisterList.Where(z => z is IXscfRazorRuntimeCompilation))
                    {
                        try
                        {
                            var libraryPath = ((IXscfRazorRuntimeCompilation)razorRegister).LibraryPath;
                            options.FileProviders.Add(new PhysicalFileProvider(libraryPath));
                        }
                        catch (Exception ex)
                        {
                            SenparcTrace.BaseExceptionLog(ex);
                        }
                    }
                });
            }
#endif

            //支持 Session
            services.AddSession();
            //解决中文进行编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            //使用内存缓存
            services.AddMemoryCache();

            //注册 SignalR
            services.AddSignalR();
            //注册 Lazy<T>
            services.AddTransient(typeof(Lazy <>));

            services.Configure <SenparcCoreSetting>(configuration.GetSection("SenparcCoreSetting"));
            services.Configure <SenparcSmsSetting>(configuration.GetSection("SenparcSmsSetting"));

            //自动依赖注入扫描
            services.ScanAssamblesForAutoDI();
            //已经添加完所有程序集自动扫描的委托,立即执行扫描(必须)
            AssembleScanHelper.RunScan();
            //services.AddSingleton<Core.Cache.RedisProvider.IRedisProvider, Core.Cache.RedisProvider.StackExchangeRedisProvider>();

            //注册 User 登录策略
            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserAnonymous", policy =>
                {
                    policy.RequireClaim("UserMember");
                });
            });
            services.AddHttpContextAccessor();

            //Repository & Service
            services.AddScoped(typeof(ISysButtonRespository), typeof(SysButtonRespository));

            //Other
            services.AddScoped(typeof(Scf.Core.WorkContext.Provider.IAdminWorkContextProvider), typeof(Scf.Core.WorkContext.Provider.AdminWorkContextProvider));
            services.AddTransient <Microsoft.AspNetCore.Mvc.Infrastructure.IActionContextAccessor, Microsoft.AspNetCore.Mvc.Infrastructure.ActionContextAccessor>();

            //激活 Xscf 扩展引擎(必须)
            services.StartEngine(configuration);
        }
        public static IServiceCollection AddMvcConfig(this IServiceCollection services, CompatibilityVersion aspCoreVersion)
        {
            services.AddMvc()
            .SetCompatibilityVersion(aspCoreVersion)
            .AddJsonOptions(options => {
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                options.SerializerSettings.ContractResolver  = new DefaultContractResolver();
            });

            return(services);
        }
Example #10
0
        public static void AddNcfServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env, CompatibilityVersion compatibilityVersion)
        {
            //如果运行在IIS中,需要添加IIS配置
            //https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/iis/index?view=aspnetcore-2.1&tabs=aspnetcore2x#supported-operating-systems
            //services.Configure<IISOptions>(options =>
            //{
            //    options.ForwardClientCertificate = false;
            //});

            //启用以下代码强制使用 https 访问
            //services.AddHttpsRedirection(options =>
            //{
            //    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
            //    options.HttpsPort = 443;
            //});

            //读取Log配置文件
            var repository = LogManager.CreateRepository("NETCoreRepository");

            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));

            //提供网站根目录
            if (env.ContentRootPath != null)
            {
                SiteConfig.ApplicationPath = env.ContentRootPath;
                SiteConfig.WebRootPath     = env.WebRootPath;
            }

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //services.AddMvc(options =>
            //{
            //    //options.Filters.Add<HttpGlobalExceptionFilter>();
            //})
            //.SetCompatibilityVersion(compatibilityVersion)
            //.AddRazorPagesOptions(options =>
            //{
            //    //options.AllowAreas = true;//支持 Area
            //    //options.AllowMappingHeadRequestsToGetHandler = false;//https://www.learnrazorpages.com/razor-pages/handler-methods
            //})


            services.AddMultiTenant();                                        //注册多租户(按需)
            EntitySetKeys.TryLoadSetInfo(typeof(SenparcEntitiesMultiTenant)); //注册多租户数据库的对象(按需)
            services.AddScoped <ITenantInfoDbData, TenantInfoDbData>();
            services.AddScoped <TenantInfoRepository>();
            services.AddScoped <IClientRepositoryBase <TenantInfo>, TenantInfoRepository>();

            services.AddSenparcGlobalServices(configuration);//注册 CO2NET 基础引擎所需服务

            var builder = services.AddRazorPages(opt =>
            {
                //opt.RootDirectory = "/";
            })
                          .AddNcfAreas(env)//注册所有 Ncf 的 Area 模块(必须)
                          .ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    var values = actionContext.ModelState.Where(_ => _.Value.ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid).Select(_ => new { _.Key, Errors = _.Value.Errors.Select(__ => __.ErrorMessage) });
                    AjaxReturnModel commonReturnModel = new AjaxReturnModel <object>(values);
                    commonReturnModel.Success         = false;
                    commonReturnModel.Msg             = "参数校验未通过";
                    //commonReturnModel.StatusCode = Core.App.CommonReturnStatusCode.参数校验不通过;
                    return(new BadRequestObjectResult(commonReturnModel));
                };
            })
                          .AddXmlSerializerFormatters()
                          .AddJsonOptions(options =>
            {
                //忽略循环引用
                //options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                //options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            })
                          //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1&tabs=aspnetcore2x
                          //.AddSessionStateTempDataProvider()
                          //忽略JSON序列化过程中的循环引用:https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
                          .AddRazorPagesOptions(options =>
            {
                //自动注册  防止跨站请求伪造(XSRF/CSRF)攻击
                options.Conventions.Add(new Core.Conventions.AutoValidateAntiForgeryTokenModelConvention());
            });

#if DEBUG
            //Razor启用运行时编译,多个项目不需要手动编译。
            if (env.IsDevelopment())
            {
                builder.AddRazorRuntimeCompilation(options =>
                {
                    //自动索引所有需要使用 RazorRuntimeCompilation 的模块
                    foreach (var razorRegister in XncfRegisterManager.RegisterList.Where(z => z is IXncfRazorRuntimeCompilation))
                    {
                        try
                        {
                            var libraryPath = ((IXncfRazorRuntimeCompilation)razorRegister).LibraryPath;
                            options.FileProviders.Add(new PhysicalFileProvider(libraryPath));
                        }
                        catch (Exception ex)
                        {
                            SenparcTrace.BaseExceptionLog(ex);
                        }
                    }
                });
            }
#endif

            //TODO:在模块中注册
            services.AddScoped <Ncf.AreaBase.Admin.Filters.AuthenticationResultFilterAttribute>();

            //支持 Session
            services.AddSession();
            //解决中文进行编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            //使用内存缓存
            services.AddMemoryCache();

            //注册 SignalR
            services.AddSignalR();
            //注册 Lazy<T>
            services.AddTransient(typeof(Lazy <>));

            services.Configure <SenparcCoreSetting>(configuration.GetSection("SenparcCoreSetting"));
            services.Configure <SenparcSmsSetting>(configuration.GetSection("SenparcSmsSetting"));

            //自动依赖注入扫描
            services.ScanAssamblesForAutoDI();
            //已经添加完所有程序集自动扫描的委托,立即执行扫描(必须)
            AssembleScanHelper.RunScan();
            //services.AddSingleton<Core.Cache.RedisProvider.IRedisProvider, Core.Cache.RedisProvider.StackExchangeRedisProvider>();

            ////添加多租户
            //services.AddMultiTenant();

            //注册 User 登录策略
            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserAnonymous", policy =>
                {
                    policy.RequireClaim("UserMember");
                });
            });
            services.AddHttpContextAccessor();

            //Repository & Service
            services.AddScoped <ISysButtonRespository, SysButtonRespository>();

            //Other
            services.AddScoped <IAdminWorkContextProvider, AdminWorkContextProvider>();
            services.AddTransient <IActionContextAccessor, ActionContextAccessor>();

            //忽略某些 API
            //Senparc.CO2NET.WebApi.Register.OmitCategoryList.Add(Senparc.NeuChar.PlatformType.WeChat_Work.ToString());
            //Senparc.CO2NET.WebApi.Register.OmitCategoryList.Add(Senparc.NeuChar.PlatformType.WeChat_MiniProgram.ToString());
            //Senparc.CO2NET.WebApi.Register.OmitCategoryList.Add(Senparc.NeuChar.PlatformType.WeChat_Open.ToString());
            //Senparc.CO2NET.WebApi.Register.OmitCategoryList.Add(Senparc.NeuChar.PlatformType.WeChat_OfficialAccount.ToString());

            //激活 Xncf 扩展引擎(必须)
            services.StartEngine(configuration);
        }
Example #11
0
        public static void AddScfServices(this IServiceCollection services, IConfiguration configuration, CompatibilityVersion compatibilityVersion)
        {
            //如果运行在IIS中,需要添加IIS配置
            //https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/iis/index?view=aspnetcore-2.1&tabs=aspnetcore2x#supported-operating-systems
            //services.Configure<IISOptions>(options =>
            //{
            //    options.ForwardClientCertificate = false;
            //});


            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc(options =>
            {
                //options.Filters.Add<HttpGlobalExceptionFilter>();
            })
            .SetCompatibilityVersion(compatibilityVersion)
            .AddRazorPagesOptions(options =>
            {
                options.AllowAreas = true;//支持 Area
                //options.AllowMappingHeadRequestsToGetHandler = false;//https://www.learnrazorpages.com/razor-pages/handler-methods
            })
            .AddScfAreas()//注册所有 Scf 的 Area 模块(必须)
            .AddXmlSerializerFormatters()
            .AddJsonOptions(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            })
            //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1&tabs=aspnetcore2x
            //.AddSessionStateTempDataProvider()
            //忽略JSON序列化过程中的循环引用:https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
            ;

            //services.AddSenparcGlobalServices(configuration);//Senparc.CO2NET 全局注册    //已经在startup.cs中注册

            //支持 AutoMapper
            services.AddAutoMapper();

            //支持 Session
            services.AddSession();
            //解决中文进行编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            //使用内存缓存
            services.AddMemoryCache();

            //注册 SignalR
            services.AddSignalR();
            //注册 Lazy<T>
            services.AddTransient(typeof(Lazy <>));

            services.Configure <SenparcCoreSetting>(configuration.GetSection("SenparcCoreSetting"))
            .AddSenparcEntitiesDI();     //SQL Server设置


            //自动依赖注入扫描
            services.ScanAssamblesForAutoDI();
            //已经添加完所有程序集自动扫描的委托,立即执行扫描(必须)
            AssembleScanHelper.RunScan();


            //注册 User 登录策略
            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserAnonymous", policy =>
                {
                    policy.RequireClaim("UserMember");
                });
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();


            services.AddScoped(typeof(ISqlClientFinanceData), typeof(SqlClientFinanceData));
        }
Example #12
0
        public void PostConfigure_DoesNotSetAllowRecompilingViewsOnFileChange_WhenNotInDevelopment(CompatibilityVersion compatibilityVersion)
        {
            // Arrange
            var options      = new RazorViewEngineOptions();
            var hostingEnv   = Mock.Of <IHostingEnvironment>(env => env.EnvironmentName == EnvironmentName.Staging);
            var optionsSetup = GetSetup(compatibilityVersion, hostingEnv);

            // Act
            optionsSetup.Configure(options);
            optionsSetup.PostConfigure(string.Empty, options);

            // Assert
            Assert.False(options.AllowRecompilingViewsOnFileChange);
        }
Example #13
0
        /// <summary>
        /// Sets the default TWCoreValues
        /// </summary>
        public static void SetDefaultTWCoreValues(this IServiceCollection services, CompatibilityVersion compatibilityVersion = CompatibilityVersion.Version_2_2, CoreWebSettings settings = null)
        {
            settings = settings ?? new CoreWebSettings();
            services.AddMvc(options =>
            {
                try
                {
                    if (settings.UseCustomXmlSerializer)
                    {
                        var xmlSerializer = new XmlTextSerializer();
                        options.AddISerializerInputFormatter(xmlSerializer);
                        options.AddISerializerOutputFormatter(xmlSerializer);
                    }
                    else
                    {
                        options.InputFormatters.Add(new XmlSerializerInputFormatter(options));
                        options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
                    }

                    if (settings.EnableFormatMapping)
                    {
                        options.FormatterMappings.SetMediaTypeMappingForFormat
                            ("xml", MediaTypeHeaderValue.Parse("application/xml"));
                        options.FormatterMappings.SetMediaTypeMappingForFormat
                            ("js", MediaTypeHeaderValue.Parse("application/json"));
                    }

                    if (settings.EnableTWCoreSerializers)
                    {
                        var serializers = SerializerManager.GetBinarySerializers();
                        foreach (var serializer in serializers)
                        {
                            options.AddISerializerInputFormatter(serializer);
                            options.AddISerializerOutputFormatter(serializer);
                            if (settings.EnableFormatMapping)
                            {
                                options.FormatterMappings.SetMediaTypeMappingForFormat(serializer.Extensions[0].Substring(1),
                                                                                       MediaTypeHeaderValue.Parse(serializer.MimeTypes[0]));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Core.Log.Write(ex);
                }
            }).SetCompatibilityVersion(compatibilityVersion)
            .AddJsonOptions(options =>
            {
                if (settings.EnableJsonStringEnum)
                {
                    options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                }
            });
            services.AddLogging(cfg =>
            {
                if (settings.EnableTWCoreLogger)
                {
                    cfg.AddTWCoreLogger();
                }
            });
            if (settings.EnableGZipCompressor)
            {
                services.Configure <GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Fastest);
                services.AddResponseCompression();
                if (settings.EnableTWCoreSerializers)
                {
                    var serializers = SerializerManager.GetBinarySerializers();

                    services.Configure <ResponseCompressionOptions>(options =>
                    {
                        options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(serializers.SelectMany(i => i.MimeTypes));
                    });
                }
            }
        }
 public static void CompatibilityVersion(this IServiceCollection serviceCollection, CompatibilityVersion version)
 {
     serviceCollection
     .AddMvc()
     .SetCompatibilityVersion(version);
 }
Example #15
0
 public static void SetupFhir(IServiceCollection services, IConfigurationRoot fhirStarterSettings, CompatibilityVersion dotNetCoreVersion)
 {
     AddFhirStarterSettings(services, fhirStarterSettings);
     RegisterServices(services, fhirStarterSettings);
 }
        /// <summary>
        /// Extension helper to configure the MVC framework (e.g. configuring Vertical-Slice Architecture for Razor views)
        /// </summary>
        /// <param name="services"></param>
        /// <param name="target">The ASP.NET Core compatibility version for the application.</param>
        /// <returns></returns>
        public static IServiceCollection AddFeatureSlicedMvc(this IServiceCollection services, CompatibilityVersion target = CompatibilityVersion.Latest)
        {
            services.AddMvc(mvcOptions =>
            {
                mvcOptions.Conventions.Add(new FeatureControllerModelConvention());
            })
            .AddRazorOptions(razorOptions =>
            {
                // {0} - Action Name
                // {1} - Controller Name
                // {2} - Area Name
                // {3} - Feature Name
                // Replace normal view location entirely
                razorOptions.ViewLocationFormats.Clear();
                razorOptions.ViewLocationFormats.Add("/Features/{3}/{0}.cshtml");     // e.g. Features/Default/Index.cshtml
                razorOptions.ViewLocationFormats.Add("/Features/{3}/{1}/{0}.cshtml"); // e.g.
                razorOptions.ViewLocationFormats.Add("/Features/Shared/{0}.cshtml");  // e.g. Features/Shared/Error.cshtml
                razorOptions.ViewLocationExpanders.Add(new FeatureViewLocationExpander());
            })
            .AddViewOptions(viewOptions =>
            {
                viewOptions.HtmlHelperOptions.ClientValidationEnabled = true;
                viewOptions.AllowRenderingMaxLengthAttribute          = true;
            })
            .SetCompatibilityVersion(target);

            return(services);
        }