Beispiel #1
0
 public static void AddAppConfiguration(WebHostBuilderContext hostingContext, IConfigurationBuilder config)
 {
     config.AddJsonFile("appsettings.json", optional: true);
 }
Beispiel #2
0
 private static void Configure(WebHostBuilderContext context, IConfigurationBuilder configurationBuilder)
 {
     configurationBuilder.AddJsonFile("appsettings.json", false, true)
     .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true, true)
     .AddJsonFile($"appsettings.local.json", true, true);
 }
Beispiel #3
0
 private static void SetupConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder configBuilder)
 {
     configBuilder.Sources.Clear();
     configBuilder.AddJsonFile("config.json", false, true)
     .AddEnvironmentVariables();
 }
Beispiel #4
0
        public static IServiceCollection AddFrameworkService(this IServiceCollection services,
                                                             Func <ActionExecutingContext, string> CsSector = null,
                                                             List <IDataPrivilege> dataPrivilegeSettings    = null,
                                                             WebHostBuilderContext webHostBuilderContext    = null
                                                             )
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();
            IConfigurationRoot config = null;

            var configBuilder =
                new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();

            if (webHostBuilderContext != null)
            {
                IHostingEnvironment env = webHostBuilderContext.HostingEnvironment;
                configBuilder
                .AddJsonFile(
                    $"appsettings.{env.EnvironmentName}.json",
                    optional: true,
                    reloadOnChange: true
                    );
            }
            config = configBuilder.Build();

            var gd = GetGlobalData();

            services.AddSingleton(gd);
            var con = config.Get <Configs>() ?? new Configs();

            if (dataPrivilegeSettings != null)
            {
                con.DataPrivilegeSettings = dataPrivilegeSettings;
            }
            else
            {
                con.DataPrivilegeSettings = new List <IDataPrivilege>();
            }
            services.AddSingleton(con);
            services.AddResponseCaching();
            services.AddMemoryCache();
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.Cookie.Name = con.CookiePre + ".Session";
                options.IdleTimeout = TimeSpan.FromSeconds(3600);
            });
            SetupDFS(con);


            var mvc   = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.dll").FirstOrDefault();
            var admin = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.Admin.dll").FirstOrDefault();

            services.AddMvc(options =>
            {
                // ModelBinderProviders
                options.ModelBinderProviders.Insert(0, new StringBinderProvider());

                // Filters
                options.Filters.Add(new DataContextFilter(CsSector));
                options.Filters.Add(new PrivilegeFilter());
                options.Filters.Add(new FrameworkFilter());
            })
            .AddJsonOptions(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

                // custom ContractResolver
                options.SerializerSettings.ContractResolver = new WTMContractResolver()
                {
                    //NamingStrategy = new CamelCaseNamingStrategy()
                };
            })
            .ConfigureApplicationPartManager(m =>
            {
                var feature = new ControllerFeature();
                if (mvc != null)
                {
                    m.ApplicationParts.Add(new AssemblyPart(mvc));
                }
                if (admin != null)
                {
                    m.ApplicationParts.Add(new AssemblyPart(admin));
                }
                m.PopulateFeature(feature);
                services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray());
            })
            .AddControllersAsServices()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressModelStateInvalidFilter  = true;
                options.InvalidModelStateResponseFactory = (a) =>
                {
                    return(new BadRequestObjectResult(a.ModelState.GetErrorJson()));
                };
            });


            services.Configure <RazorViewEngineOptions>(options =>
            {
                if (mvc != null)
                {
                    options.FileProviders.Add(
                        new EmbeddedFileProvider(
                            mvc,
                            "WalkingTec.Mvvm.Mvc" // your external assembly's base namespace
                            )
                        );
                }
                if (admin != null)
                {
                    options.FileProviders.Add(
                        new EmbeddedFileProvider(
                            admin,
                            "WalkingTec.Mvvm.Mvc.Admin" // your external assembly's base namespace
                            )
                        );
                }
            });

            services.Configure <FormOptions>(y =>
            {
                y.ValueLengthLimit         = int.MaxValue;
                y.MultipartBodyLengthLimit = con.FileUploadOptions.UploadLimit;
            });

            services.AddSingleton <IUIService, DefaultUIService>();
            GlobalServices.SetServiceProvider(services.BuildServiceProvider());
            return(services);
        }
 public static void AddConsoleIfEnabled(this ILoggingBuilder builder, WebHostBuilderContext context)
 {
     AddConsoleIfEnabled(builder, context.HostingEnvironment.IsDevelopment(), context.Configuration);
 }
        /// <summary>
        /// Adds a Functions Framework console logger, either using a "single line per log entry"
        /// plain text format (with separate lines for scopes and exceptions, when present) or a JSON format,
        /// depending on the execution environment.
        /// </summary>
        /// <param name="builder">The logging builder to add the logger to.</param>
        /// <param name="context">The context of the web host builder being configured.</param>
        /// <returns>The original builder, for method chaining.</returns>
        public static ILoggingBuilder AddFunctionsConsoleLogging(this ILoggingBuilder builder, WebHostBuilderContext context)
        {
            var             options  = FunctionsFrameworkOptions.FromConfiguration(context.Configuration);
            ILoggerProvider provider = options.JsonLogging
                ? new FactoryLoggerProvider(category => new JsonConsoleLogger(category, System.Console.Out))
                : new FactoryLoggerProvider(category => new SimpleConsoleLogger(category, System.Console.Out));

            builder.AddProvider(provider);
            return(builder);
        }
Beispiel #7
0
 private static void ConfigureSerilog(WebHostBuilderContext context, LoggerConfiguration configuration)
 {
     configuration.ReadFrom.Configuration(context.Configuration);
 }
Beispiel #8
0
 private static void ConfigureLogging(WebHostBuilderContext hostingContext, ILoggingBuilder logging)
 {
     logging.ClearProviders();
     logging.AddConsole();
     logging.AddDebug();
 }
Beispiel #9
0
 private void ConfigureAppConfiguration(WebHostBuilderContext hostingContext, IConfigurationBuilder config)
 {
     HostingEnvironment = hostingContext.HostingEnvironment;
     Configuration      = config.Build();
 }
Beispiel #10
0
        public void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)
        {
            services.AddDbContext <SGContDbContext> (options =>
                                                     options.UseNpgsql(context.Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("SGCont")));

            services.AddSignalR();

            services.AddIdentity <Usuario, IdentityRole> ()
            .AddEntityFrameworkStores <SGContDbContext> ()
            .AddDefaultTokenProviders();

            services.AddTransient <SGContDbContext> ();
            services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options => {
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = "https://microapp.cu",
                    ValidAudience    = "https://microapp.cu",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("Admin123*1234567890"))
                };
            });

            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Version        = "v1",
                    Title          = "SGCont API",
                    Description    = "Sistema de Gestión de Contratos",
                    TermsOfService = new Uri("https://example.com/terms"),
                    Contact        = new OpenApiContact {
                        Name  = "Alejandro Román Franco",
                        Email = "*****@*****.**",
                        Url   = new Uri("https://alejo.com/")
                    }
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            services.AddTransient <SGContDbContext> ();
            services.AddSingleton <MenuLoader> ();
            services.AddSingleton <LicenciaService> ();

            services.AddSpaStaticFiles(config => {
                config.RootPath = context.Configuration.GetValue <string> ("ClientApp");
            });
            services.AddCors();
            var mvcBuilder = services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(options => {
                options.SerializerSettings.Formatting = Formatting.Indented;
            });
            var lista = new string[] {
                "SGCont"
            };
            var asseblies = AppDomain.CurrentDomain.GetAssemblies().Where(c => lista.Contains(c.FullName));

            foreach (var assembly in asseblies)
            {
                mvcBuilder.AddApplicationPart(assembly);
            }
        }
Beispiel #11
0
 /// <summary>
 /// Adds required services to the service collection within the given web host builder for the Functions Framework
 /// to use a target function from the given assembly. If the Functions Framework configuration within the web host
 /// builder (typically provided by command line arguments or environment variables)
 /// does not specify a target function, the assembly is scanned for a single compatible function type.
 /// </summary>
 /// <remarks>
 /// If this method completes successfully, a binding for <see cref="IHttpFunction"/> will definitely
 /// have been added to the service collection. Other bindings may also be present, in order to adapt
 /// the function to <see cref="IHttpFunction"/>.
 /// </remarks>
 /// <param name="services">The service collection to configure.</param>
 /// <param name="context">The context of the web host builder being configured.</param>
 /// <param name="assembly">The assembly expected to contain the Functions Framework target function.</param>
 /// <returns>The original builder, for method chaining.</returns>
 public static IServiceCollection AddFunctionTarget(this IServiceCollection services, WebHostBuilderContext context, Assembly assembly) =>
 AddFunctionTarget(services, HostingInternals.GetFunctionTarget(context.Configuration, assembly));
Beispiel #12
0
 private static void SetupLogging(WebHostBuilderContext hostingContext, ILoggingBuilder loggingBuilder)
 {
     loggingBuilder.AddSerilog();
 }
Beispiel #13
0
 /// <summary>
 /// 根据环境变量组合appsettings.json
 /// 服务器的系统环境变量中需要添加:ASPNETCORE_ENVIRONMENT=Production
 /// </summary>
 /// <param name="context"></param>
 /// <param name="builder"></param>
 /// <returns></returns>
 public static void Appsettings(WebHostBuilderContext context, IConfigurationBuilder builder)
 {
     builder.AddJsonFile("appsettings.json", optional: false)
     .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true)
     .AddEnvironmentVariables();
 }
Beispiel #14
0
 protected override void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)
 {
     base.ConfigureServices(context, services);
     services.AddHttpContextAccessor();
     services.AddScoped <MyId>();
 }
Beispiel #15
0
 static void ConfigConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder config)
 {
     config.SetBasePath(Directory.GetCurrentDirectory())
     .AddJsonFile("appsettings.json", false, true)
     .AddEnvironmentVariables();
 }
Beispiel #16
0
 public HostServiceProvider(WebHostBuilderContext context)
 {
     _context = context;
 }
Beispiel #17
0
 static void ConfigureLogger(WebHostBuilderContext ctx, ILoggingBuilder logging)
 {
     logging.AddConfiguration(ctx.Configuration.GetSection("Logging"));
     logging.AddConsole();
     logging.AddDebug();
 }
        protected override void ConfigureAppConfiguration(WebHostBuilderContext hostingContext, IConfigurationBuilder config)
        {
            var environmentName = hostingContext.HostingEnvironment.EnvironmentName;

            Program.LoadConfigurations(config, environmentName);
        }
Beispiel #19
0
 public abstract void ConfigureServices(WebHostBuilderContext context, IServiceCollection services);
Beispiel #20
0
 private static void SetupConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder builder)
 {
 }
Beispiel #21
0
 protected virtual void ConfigureConfigurationOptions(WebHostBuilderContext context, IConfigurationBuilder builder)
 {
 }
Beispiel #22
0
 public override void ConfigureServices(WebHostBuilderContext context, IServiceCollection services) =>
 services.AddSingleton <IClock>(new FakeClock(Instant.FromUtc(2015, 6, 3, 20, 25, 30)));
Beispiel #23
0
 private static void InitializeLogging(ILoggingBuilder logging, WebHostBuilderContext hostingContext)
 {
     logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
     logging.AddConsole();
     logging.AddDebug();
 }
Beispiel #24
0
 public Startup(WebHostBuilderContext hostBuilderContext, MsLogger startupLogger)
 {
     Configuration = hostBuilderContext.Configuration;
     Environment   = hostBuilderContext.HostingEnvironment;
     StartupLogger = startupLogger;
 }
Beispiel #25
0
 public Startup(Type startuModuleType, WebHostBuilderContext context, Action <BootstrapperCreationOptions> optionsAction)
 {
     _startuModuleType = startuModuleType;
     _context          = context;
     _optionsAction    = optionsAction;
 }
Beispiel #26
0
 static void ConfigConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder config)
 {
     config.SetBasePath(Directory.GetCurrentDirectory())
     .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
     .AddJsonFile($"appsettings.{ctx.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
 }
Beispiel #27
0
 private static void ConfigureLogging(WebHostBuilderContext hostingContext, ILoggingBuilder logging)
 {
     logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
     logging.AddConsole();
     logging.AddDebug();
 }
Beispiel #28
0
 private static void ConfigureKestrel(WebHostBuilderContext context, KestrelServerOptions options)
 {
 }
Beispiel #29
0
        //public static IHost BuildWebHost<TStartup>(string[] args)
        //    where TStartup : class
        //{
        //    var webHost = Host.CreateDefaultBuilder(args)
        //        .ConfigureWebHostDefaults(webBuilder =>
        //        {
        //            webBuilder.UseSerilog();
        //            webBuilder.UseKestrel();

        //            webBuilder.ConfigureKestrel((context, opts) =>
        //            {
        //                opts.AddServerHeader = false;
        //                opts.Limits.MaxRequestBodySize = null;
        //                opts.Limits.MaxResponseBufferSize = null;
        //            }); //needed for IIS in-process


        //            webBuilder
        //                .UseContentRoot(Directory.GetCurrentDirectory());

        //            webBuilder.ConfigureAppConfiguration(AddAppConfiguration);

        //            webBuilder.ConfigureLogging(
        //                (hostingContext, logging) => { });

        //            webBuilder.UseDefaultServiceProvider((context, options) => { });

        //            webBuilder.UseStartup<TStartup>();


        //            //webBuilder.UseIIS(x=>x); // needs to be there for iis in process integration
        //            //webBuilder.UseIISIntegration(); // needs to be there too for iis out of process integration

        //        });


        //    return webHost.Build();

        //}


        public static void AddAppConfiguration(WebHostBuilderContext hostingContext, IConfigurationBuilder config)
        {
            config.ConfigureConfigSources();
        }
        public void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)
        {
            #region Add a PasswordHasher (optional)

            services.AddTransient <IPasswordHasher <ApplicationUser>, Sha512PasswordHasher>();

            #endregion

            #region Add an UserDbContext (required)

            services.AddUserDbContext <FileBlobUserDb>(options =>
            {
                options.ConnectionString = @"c:\temp\identityserver_legacy\storage\users";
                options.CryptoService    = new DefaultCryptoService("My super pa33wo4d 1234567890");

                options.ManageAccountEditor = new ManageAccountEditor()
                {
                    AllowDelete            = false,
                    ShowChangeEmailPage    = true,
                    ShowChangePasswordPage = true,
                    ShowTfaPage            = true,
                    EditorInfos            = new[]
                    {
                        KnownUserEditorInfos.ReadOnlyUserName(),
                        KnownUserEditorInfos.ReadOnlyEmail(),
                        KnownUserEditorInfos.GivenName(),
                        KnownUserEditorInfos.FamilyName(),
                        KnownUserEditorInfos.Organisation(),
                        KnownUserEditorInfos.PhoneNumber(),
                        KnownUserEditorInfos.BirthDate(),
                        new EditorInfo("Ranking", typeof(int))
                        {
                            Category = "Advanced", ClaimName = "ranking"
                        },
                        new EditorInfo("Cost", typeof(double))
                        {
                            Category = "Advanced", ClaimName = "cost"
                        },
                        new EditorInfo("SendInfos", typeof(bool))
                        {
                            Category = "Privacy", ClaimName = "send_infos"
                        }
                    }
                };

                options.AdminAccountEditor = new AdminAccountEditor()
                {
                    AllowDelete      = true,
                    AllowSetPassword = true,
                    EditorInfos      = new[]
                    {
                        KnownUserEditorInfos.EditableEmail(),
                        KnownUserEditorInfos.GivenName(),
                        KnownUserEditorInfos.FamilyName(),
                        new EditorInfo("Ranking", typeof(int))
                        {
                            Category = "Advanced", ClaimName = "ranking"
                        },
                        new EditorInfo("Cost", typeof(double))
                        {
                            Category = "Advanced", ClaimName = "cost"
                        },
                    }
                };
            });

            #endregion

            #region Add RoleDbContext (optional)

            //services.AddRoleDbContext<InMemoryRoleDb>();
            services.AddRoleDbContext <FileBlobRoleDb>(options =>
            {
                options.ConnectionString = @"c:\temp\identityserver_legacy\storage\roles";
            });

            #endregion

            #region Add a ResourceDbContext (required)


            services.AddResourceDbContext <FileBlobResourceDb>(options =>
            {
                options.ConnectionString    = @"c:\temp\identityserver_legacy\storage\resources";
                options.CryptoService       = new Base64CryptoService();
                options.InitialApiResources = new ApiResourceModel[]
                {
                    new ApiResourceModel("api1", "My Api1"),
                    new ApiResourceModel("api2", "My Api2")
                };
                options.InitialIdentityResources = new IdentityResourceModel[]
                {
                };
            });


            /*
             * services.AddResourceDbContext<MongoBlobResourceDb>(options =>
             * {
             *  options.ConnectionString = context.Configuration["ConnectionStrings:MongoDb"]; //"mongodb://*****:*****@"c:\temp\identityserver_legacy\storage\clients";
                options.CryptoService    = new Base64CryptoService();
                options.IntialClients    = new ClientModel[]
                {
                    new ClientModel()
                    {
                        ClientId      = "client",
                        ClientSecrets = new SecretModel[]
                        {
                            new SecretModel()
                            {
                                Value = "secret1".ToSha256()
                            },
                            new SecretModel()
                            {
                                Value = "secret2".ToSha256()
                            }
                        },
                        AllowedGrantTypes = { GrantTypes.ClientCredentials, GrantTypes.Password },
                        AllowedScopes     = { "api1", "api2", "profile", "openid" }
                    },
                    new ClientModel()
                    {
                        ClientId      = "mvc",
                        ClientSecrets = new SecretModel[]
                        {
                            new SecretModel()
                            {
                                Value = "secret".ToSha256()
                            }
                        },
                        AllowedGrantTypes = { GrantTypes.AuthorizationCode },
                        AllowedScopes     = { "openid", "profile", "api1", "email", "role", "address", "phone" },

                        AlwaysSendClientClaims           = true,
                        AlwaysIncludeUserClaimsInIdToken = true,

                        AllowOfflineAccess = true,
                        RequireConsent     = false,
                        RequirePkce        = true,

                        RedirectUris           = new string[] { "https://*****:*****@"c:\temp\identityserver_legacy\storage-export\clients";
                options.CryptoService    = new ClearTextCryptoService();
                options.BlobSerializer   = new JsonBlobSerializer()
                {
                    JsonFormatting = Newtonsoft.Json.Formatting.Indented
                };
            });

            #endregion

            #region Add ExportResourceDbContext (optional)

            services.AddExportResourceDbContext <FileBlobResourceExportDb>(options =>
            {
                options.ConnectionString = @"c:\temp\identityserver_legacy\storage-export\resources";
                options.CryptoService    = new ClearTextCryptoService();
                options.BlobSerializer   = new JsonBlobSerializer()
                {
                    JsonFormatting = Newtonsoft.Json.Formatting.Indented
                };
            });

            #endregion

            #region App SecretsVaultDbContext (optional)

            services.AddSecretsVaultDbContext <FileBlobSecretsVaultDb, SigningCredentialCertStoreCryptoService>(options =>
            {
                options.ConnectionString = @"c:\temp\identityserver_legacy\storage\secretsvault";
                options.CryptoService    = new Base64CryptoService();
            });

            #endregion

            #region UI (required)

            services.Configure <UserInterfaceConfiguration>(options =>
            {
                options.ApplicationTitle   = "IdentityServer.Legacy.Test"; // required
                options.OverrideCssContent = Properties.Resources.is4_overrides;
                options.MediaContent       = new Dictionary <string, byte[]>()
                {
                    { "openid-logo.png", Properties.Resources.openid_logo }
                };
            });

            #endregion

            #region EmailSender (required)

            services.AddTransient <ICustomEmailSender, MailJetEmailSender>();

            #endregion

            #region Login BotDetection (optional)

            services.AddLoginBotDetection <LoginBotDetection>();
            services.AddCaptchaRenderer <CaptchaCodeRenderer>();

            #endregion
        }