Пример #1
0
        public Startup(IHostingEnvironment env)
        {
            HostingEnvironment = env;

            // Set up configuration sources.
            var builder = new ConfigurationBuilder();

            builder.SetBasePath(env.GetConfigPath());
            builder.AddJsonFile("appsettings.json")
            .AddEnvironmentVariables();
            Configuration = ConfigurationHelper.Configuration = builder.Build();
        }
Пример #2
0
        private static void LoadLogManager(IHostingEnvironment env, IConfiguration config)
        {
            /*ConfigureNLog()会忽略异常,此处手动设置*/
            //env.ConfigureNLog("nlog.config");

            var nlogCfgFile = Path.Combine(env.GetConfigPath(), $"nlog.{env.EnvironmentName}.config");

            if (!File.Exists(nlogCfgFile))
            {
                nlogCfgFile = Path.Combine(env.GetConfigPath(), "nlog.config");
            }

            var logsDir = config["Logging:LogsDir"];

            if (string.IsNullOrEmpty(logsDir))
            {
                logsDir = Path.Combine(env.ContentRootPath, "logs");
            }

            NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(nlogCfgFile, false);
            NLog.LogManager.Configuration.Variables["logs-dir"] = logsDir;
        }
        public static IServiceCollection AddBearerAuthentication(this IServiceCollection services, Action <ApiKeyOptions> configure = null)
        {
            var opts = new ApiKeyOptions();

            if (configure != null)
            {
                configure.Invoke(opts);
            }

            IHostingEnvironment env    = services.BuildServiceProvider().GetRequiredService <IHostingEnvironment>();
            IConfiguration      config = services.BuildServiceProvider().GetRequiredService <IConfiguration>();

            var provider = new ApiKeyProvider(opts);

            provider.UseStorage(new ApiKeyFileStorage(env.GetConfigPath("api-keys.json")));
            provider.UseStorage(new ApiKeyConfigStorage(config));

            var validator = new BearerTokenValidator(provider);

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = HttpSysDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.SecurityTokenValidators.Add(validator);

                options.Events = new JwtBearerEvents()
                {
                    OnMessageReceived = ctx =>
                    {
                        validator.OnReceivingToken(ctx);
                        return(System.Threading.Tasks.Task.FromResult(0));
                    },
                    OnTokenValidated = ctx =>
                    {
                        validator.OnValidatedToken(ctx);
                        return(System.Threading.Tasks.Task.FromResult(0));
                    }
                };
            });

            return(services.AddSingleton <IApiKeyProvider>(provider));
        }
        public static IServiceCollection AddApiKeyProvider(this IServiceCollection services, Action <ApiKeyOptions> o = null)
        {
            var options = new ApiKeyOptions();

            if (o != null)
            {
                o.Invoke(options);
            }

            IHostingEnvironment env    = services.BuildServiceProvider().GetRequiredService <IHostingEnvironment>();
            IConfiguration      config = services.BuildServiceProvider().GetRequiredService <IConfiguration>();

            var provider = new ApiKeyProvider(options);

            provider.UseStorage(new ApiKeyFileStorage(env.GetConfigPath("api-keys.json")));
            provider.UseStorage(new ApiKeyConfigStorage(config));

            return(services.AddSingleton <IApiKeyProvider>(provider));
        }
        public UEditorOption(IHostingEnvironment hostEnv)
        {
            var cfgPath = Path.Combine(hostEnv.GetConfigPath(), "ueditor.json");

            if (!File.Exists(cfgPath))
            {
                throw new FileNotFoundException($"配置文件 {cfgPath} 不存在");
            }

            try
            {
                var json = File.ReadAllText(cfgPath, Encoding.UTF8);
                Items = JObject.Parse(json);
            }
            catch (Exception ex)
            {
                throw new InvalidDataException($"配置文件 {cfgPath} 格式错误:{ex.Message}");
            }
        }
        // This method gets called by a runtime.
        // Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            //
            // IHttpContextAccessor
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            //
            // Logging
            services.AddApiLogging();

            //
            // Auditing
            services.AddApiAuditing();

            //
            // Files
            services.AddFileProvider();

            //
            // Load plugins
            ModuleConfig modConfig = new ModuleConfig(_hostingEnv.GetConfigPath("modules.json"));
            ModuleLoader loader    = new ModuleLoader(_hostingEnv);

            LoadPlugins(loader, modConfig.Modules);
            AdminHost.Instance.ConfigureModules(services);

            //
            // CORS
            services.AddCors();

            //
            // Authentication
            services.AddBearerAuthentication();

            //
            // Authorization
            services.AddAuthorizationPolicy();

            services.AddConfigurationWriter(_hostingEnv);

            //
            // Antiforgery
            services.TryAddSingleton <IAntiforgeryTokenStore, AntiForgeryTokenStore>();
            services.AddAntiforgery(o => {
                o.RequireSsl = true;
                o.CookieName = o.FormFieldName = HeaderNames.XSRF_TOKEN;
            });

            //
            // Caching
            services.AddMemoryCache();

            //
            // MVC
            IMvcBuilder builder = services.AddMvc(o => {
                // Replace default json output formatter
                o.OutputFormatters.RemoveType <AspNetCore.Mvc.Formatters.JsonOutputFormatter>();

                var settings = JsonSerializerSettingsProvider.CreateSerializerSettings();
                o.OutputFormatters.Add(new JsonOutputFormatter(settings, System.Buffers.ArrayPool <char> .Shared));

                // TODO
                // Workaround filter to fix Object Results returned from controllers
                // Remove when https://github.com/aspnet/Mvc/issues/4960 is resolved
                o.Filters.Add(typeof(Fix4960ActionFilter));

                o.Filters.Add(typeof(ActionFoundFilter));

                o.Filters.Add(typeof(ResourceInfoFilter));

                RemoveFilter <UnsupportedContentTypeFilter>(o);
            });

            foreach (var asm in loader.GetAllLoadedAssemblies())
            {
                builder.AddApplicationPart(asm);
            }

            builder.AddControllersAsServices();
            builder.AddWebApiConventions();
        }
        public static void AddConfigurationWriter(this IServiceCollection services, IHostingEnvironment hostingEnvironment)
        {
            var writer = new ConfigurationWriter(hostingEnvironment.GetConfigPath(ConfigurationHelper.APPSETTINGS_NAME));

            services.TryAddSingleton <IConfigurationWriter>(writer);
        }