Пример #1
0
 protected virtual void ConfigureWebHost(IWebHostBuilder webHostBuilder)
 {
     TestAppHostBuilder?.Implementation?.InvokePreBuilders(webHostBuilder);
     ConfigureWebServer(webHostBuilder);
     webHostBuilder.Configure((context, builder) => {
         ConfigureWebApp(context, builder);
         AppHostBuilder.UsePlugins <IConfigureWebAppPlugin>(context, builder, Plugins);
     });
     UseWebHostPlugins(webHostBuilder);
     TestAppHostBuilder?.Implementation?.InvokePostBuilders(webHostBuilder);
 }
Пример #2
0
        /// <summary>
        /// Setups the service endpoints.
        /// </summary>
        private void SetupServiceEndpoints()
        {
            _webBuilder.Configure(app =>
            {
                // Add a probe endpoint that can be used to check the application is still alive.
                EnableProbeEndpoint(app);

                // Add an endpoint for each hosted process.
                EnableProcessEndpoints(app);

                // Add swagger like documentation.
                EnableSwaggerEndpoint(app);
            });
        }
Пример #3
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder
            .Configure(app => app.UseGraphQL("/"))
            .ConfigureServices(services =>
            {
                // Create a new service provider.
                var serviceProvider = new ServiceCollection()
                                      .AddEntityFrameworkInMemoryDatabase()
                                      .AddEntityFrameworkProxies()
                                      .BuildServiceProvider();

                // Add a database context (AppDbContext) using an in-memory
                // database for testing.
                services.AddDbContext <AppDbContext>(options =>
                {
                    options.UseInMemoryDatabase("TestDB");
                    options.UseLazyLoadingProxies();
                    options.UseInternalServiceProvider(serviceProvider);
                });

                services.AddScoped <IDomainEventDispatcher, NoOpDomainEventDispatcher>();
                services.AddScoped <IRepository, EfRepository>();

                services.AddGraphQL(sp => SchemaBuilder.New()
                                    .AddServices(sp)
                                    .AddQueryType <QueryType>()
                                    .AddMutationType <MutationType>()
                                    .BindClrType <Guid, IdType>()
                                    .Create());

                // Build the service provider.
                var sp = services.BuildServiceProvider();

                // Create a scope to obtain a reference to the database
                // context (AppDbContext).
                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var db             = scopedServices.GetRequiredService <AppDbContext>();

                    // Ensure the database is created.
                    db.Database.EnsureCreated();

                    // Seed the database with test data.
                    SeedData.PopulateTestData(db);
                }
            });
        }
        public static IWebHostBuilder EnableDiscoveryServer(this IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                RegisterDependencyInjections(services);
                RegisterAppsController(services);
            });

            builder.Configure(app =>
            {
                app.UseMiddleware(typeof(ErrorHandlingMiddleware));
            });

            return(builder);
        }
Пример #5
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.Configure((ctx, app) => {
                app.UseWebSockets();
                app.UseFusionSession();

                // API controllers
                app.UseRouting();
                app.UseEndpoints(endpoints => {
                    endpoints.MapControllerRoute(name: "DefaultApi", pattern: "api/{controller}/{action}");
                    endpoints.MapControllers();
                    endpoints.MapFusionWebSocketServer();
                });
            });
        }
Пример #6
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                // Mock DB and IdentityServices

                services.AddDbContext <MindNote.Backend.Identity.Data.ApplicationDbContext>(options =>
                {
                    options.UseInMemoryDatabase(Guid.NewGuid().ToString());
                });

                services.AddDefaultIdentity <IdentityUser>()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores <MindNote.Backend.Identity.Data.ApplicationDbContext>();

                services.AddIdentityServer(options =>
                {
                    options.PublicOrigin    = Utils.ServerConfiguration.Identity;
                    options.UserInteraction = new IdentityServer4.Configuration.UserInteractionOptions
                    {
                        LoginUrl  = "/Identity/Account/Login",
                        LogoutUrl = "/Identity/Account/Logout",
                        ErrorUrl  = "/Identity/Account/Error",
                    };
                })
                .AddDeveloperSigningCredential()
                .AddInMemoryIdentityResources(SampleConfig.GetIdentityResources())
                .AddInMemoryApiResources(SampleConfig.GetApiResources())
                .AddInMemoryClients(new[] {
                    new Client
                    {
                        ClientId          = ClientId,
                        ClientSecrets     = new [] { new Secret(ClientSecret.Sha256()) },
                        AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                        AllowedScopes     = { SampleConfig.APIScope }
                    }
                })
                .AddTestUsers(users);

                Startup.ConfigureFinalServices(null, services);
            });

            builder.Configure(app =>
            {
                Startup.ConfigureApp(null, app, null);
            });
        }
        public static IWebHostBuilder UseStartup(this IWebHostBuilder builder, Type startupType)
        {
            var typeInfo     = startupType.GetTypeInfo();
            var constructors = typeInfo.GetConstructors()
                               .Where(x => x.IsPublic)
                               .OrderBy(x => x.GetParameters().Length);

            IStartup startup = null;

            foreach (var constructor in constructors)
            {
                var parameters = constructor.GetParameters();
                var objParams  = new object[parameters.Length];
                int i          = 0;
                for (i = 0; i < parameters.Length; i++)
                {
                    if (DefaultParamterValue.TryGetDefaultValue(parameters[i], out var value))
                    {
                        objParams[i] = value;
                        var x = new ConfigurationBuilder();
                    }
                    else
                    {
                        break;
                    }
                }

                if (i < parameters.Length)
                {
                    continue;
                }

                startup = (IStartup)constructor.Invoke(objParams);
                break;
            }

            if (startup == null)
            {
                throw new InvalidOperationException("操作失败,无法构造出Startup类");
            }

            return(builder.Configure(
                       services => startup.ConfigureServices(services),
                       app => startup.Configure(app)));
        }
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                services.AddInMemoryDataAccessServices <TDbContext>();
            });

            builder.Configure(builder =>
            {
                using (var serviceScope = builder.ApplicationServices.CreateScope())
                {
                    var services  = serviceScope.ServiceProvider;
                    var dbContext = services.GetService <TDbContext>();

                    // INSERT [dbo].[AspNetUsers] ([Id], [UserName], [NormalizedUserName], [Email], [NormalizedEmail], [EmailConfirmed], [PasswordHash], [SecurityStamp], [ConcurrencyStamp], [PhoneNumber], [PhoneNumberConfirmed], [TwoFactorEnabled], [LockoutEnd], [LockoutEnabled], [AccessFailedCount], [FullName]) VALUES (N'2fd44c75-4c08-4723-82dc-efd21d578627', N'*****@*****.**', N'*****@*****.**', N'*****@*****.**', N'*****@*****.**', 0, N'AQAAAAEAACcQAAAAELDzmzW/2zZATdC1rhDbDBEHWYziIPV6U2mOtAXfKFUgIg1vtPXlgOetL8tBPKuSrg==', N'4ZGZFFTIFBZVLFDGY7ZQ4O74R3ZOCCJM', N'81ba8fc8-6db7-4ae4-9574-4729473c60c2', NULL, 0, 0, NULL, 1, 0, N'Test User')
                    var count = dbContext.Database.ExecuteSqlRaw("INSERT AspNetUsers ([Id], [UserName], [NormalizedUserName], [Email], [NormalizedEmail], [EmailConfirmed], [PasswordHash], [SecurityStamp], [ConcurrencyStamp], [PhoneNumber], [PhoneNumberConfirmed], [TwoFactorEnabled], [LockoutEnd], [LockoutEnabled], [AccessFailedCount], [FullName]) VALUES (N'2fd44c75-4c08-4723-82dc-efd21d578627', N'*****@*****.**', N'*****@*****.**', N'*****@*****.**', N'*****@*****.**', 0, N'AQAAAAEAACcQAAAAELDzmzW/2zZATdC1rhDbDBEHWYziIPV6U2mOtAXfKFUgIg1vtPXlgOetL8tBPKuSrg==', N'4ZGZFFTIFBZVLFDGY7ZQ4O74R3ZOCCJM', N'81ba8fc8-6db7-4ae4-9574-4729473c60c2', NULL, 0, 0, NULL, 1, 0, N'Test User')");
                }
            });
        }
    public static void ConfigureWebHost(IWebHostBuilder builder, Func <string, string?> getSetting, Type?motorStartup)
    {
        IMotorStartup?startup = null;

        if (motorStartup is not null)
        {
            startup = Activator.CreateInstance(motorStartup) as IMotorStartup;
        }

        var          urls       = builder.GetSetting(WebHostDefaults.ServerUrlsKey);
        const string defaultUrl = "http://0.0.0.0:9110";

        if (string.IsNullOrEmpty(urls))
        {
            builder.UseUrls(defaultUrl);
        }
        else if (!urls.Contains(defaultUrl))
        {
            builder.UseUrls($"{urls};{defaultUrl}");
        }

        builder.Configure((context, applicationBuilder) =>
        {
            applicationBuilder.UseRouting();
            var enablePrometheusSetting = getSetting(MotorHostDefaults.EnablePrometheusEndpointKey);
            if (string.IsNullOrEmpty(enablePrometheusSetting) || bool.Parse(enablePrometheusSetting))
            {
                applicationBuilder.UsePrometheusServer();
            }

            startup?.Configure(context, applicationBuilder);
            applicationBuilder.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/health"); });
        });
        if (motorStartup is not null)
        {
            builder.UseSetting(WebHostDefaults.ApplicationKey, motorStartup.Assembly.GetName().Name);
        }

        builder.ConfigureServices((context, collection) =>
        {
            startup?.ConfigureServices(context, collection);
        });
    }
Пример #10
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                //var descriptor = services.SingleOrDefault(
                //    d => d.ServiceType ==
                //        typeof(DbContextOptions<ApplicationDbContext>));
                //services.Remove(descriptor);
                //services.AddDbContext<ApplicationDbContext>(options =>
                //{
                //    options.UseInMemoryDatabase("InMemoryDbForTesting");
                //});

                var sp = services.BuildServiceProvider();
                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var logger         = scopedServices
                                         .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >();

                    //var db = scopedServices.GetRequiredService<ApplicationDbContext>();
                    //db.Database.EnsureCreated();
                    //try
                    //{
                    //    Utilities.InitializeDbForTests(db);
                    //}
                    //catch (Exception ex)
                    //{
                    //    logger.LogError(ex, "An error occurred seeding the " +
                    //        "database with test messages. Error: {Message}", ex.Message);
                    //}
                }
            });

            builder.CaptureStartupErrors(true);
            builder.Configure(app =>
            {
                var logger = app.ApplicationServices.GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >();
                LogMiddlleware(app, logger);
            });
        }
 protected override void ConfigureWebHost(IWebHostBuilder builder)
 {
     builder.ConfigureServices(services =>
     {
         signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
         services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
         services.AddMemoryCache();
         services.AddHttpContextAccessor();
         services.AddAPIRateLimiterUserId(options =>
         {
             options.GlobalRateLimit = 10;
             options.GlobalSpan      = TimeSpan.FromMinutes(30);
             options.ExcludeList     = new List <string>
             {
                 "127.0.0.1", "192.168.0.0/24"
             };
             options.UserIdClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier";
         }).AddRedisCacheProvider(() => "127.0.0.1:6379").AddMongoBackupProvider(options =>
         {
             options.MongoCollectionName   = "UserIdRecords";
             options.MongoDbName           = "UserIdLimit";
             options.MongoConnectionString = "mongodb://localhost:27017";
         });;
         services.AddAuthentication(o =>
         {
             o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
             o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
         }).AddDefaultBearerAuth(options =>
         {
             options.Issuer             = issure;
             options.Audience           = audience;
             options.SignKey            = signingKey;
             options.SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
         });
     });
     builder.Configure(app =>
     {
         app.UseAuthentication();
         app.UseMvc();
     });
 }
Пример #12
0
        public static void ConfigureWebApplication(IWebHostBuilder cfg)
        {
            var port        = Environment.GetEnvironmentVariable("SERVICE_PORT") ?? "5000";
            var servicePort = int.Parse(port);

            // Setup a HTTP/2 endpoint without TLS.
            cfg.ConfigureKestrel(options =>
            {
                // https://docs.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-5.0#unable-to-start-aspnet-core-grpc-app-on-macos
                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    options.ListenLocalhost(servicePort, o => o.Protocols = HttpProtocols.Http2);
                }
                else
                {
                    options.ListenAnyIP(servicePort, o => o.Protocols = HttpProtocols.Http2);
                }
            });

            cfg.Configure((ctx, app) =>
            {
                if (ctx.HostingEnvironment.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }

                app.UseRouting();

                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapGrpcService <PaycheckService>();

                    endpoints.MapGet("/", async context =>
                    {
                        await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
                    });
                });
            });
        }
Пример #13
0
        void ConfigureApp() =>
        _builder.Configure(app =>
        {
            var environment = app.ApplicationServices.GetRequiredService <Microsoft.Extensions.Hosting.IHostingEnvironment>();

            if (environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseMvc(_configure.ConfigureMvcRoutes);

            app.UseSignalR(routes =>
            {
                routes.MapQueryHub();

                _configure.ConfigureSignalRRoutes(routes);
            });

            _configure.ConfigureApp(app);
        });
Пример #14
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            var conf = (IConfiguration) new ConfigurationBuilder()
                       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                       .Build();

            var env = new ContextService(InstanceContext.IntegrationTest);
            var map = new MapperConfiguration(x => x.AddProfile <AutoMapperProfile_EFCore_TBL>()).CreateMapper();

            builder.ConfigureServices(sc =>
            {
                sc.AddSingleton <IConfiguration>(conf);
                sc.AddSingleton <IContextService>(env);
                sc.AddSingleton <IMapper>(map);
                sc.AddScoped <IUnitOfWork, UnitOfWork>(_ =>
                {
                    var uow = new UnitOfWork(conf["Databases:IdentityEntities_EFCore_Tbl"], env);

                    var data = new DefaultDataFactory_Tbl(uow);
                    data.CreateSettings();

                    return(uow);
                });
                sc.AddSingleton <IDefaultDataFactory_Tbl, DefaultDataFactory_Tbl>();
                sc.AddSingleton <IOAuth2JwtFactory, OAuth2JwtFactory>();

                sc.AddControllers()
                .AddNewtonsoftJson(opt =>
                {
                    opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                })
                //https://github.com/aspnet/Mvc/issues/5992
                .AddApplicationPart(typeof(BaseController).Assembly);
            });

            builder.Configure(app => { });
        }
Пример #15
0
        public void Configure(IWebHostBuilder builder)
        {
            Console.WriteLine("This is CustomHostingStartup Invoke");

            //有IWebHostBuilder,一切都可以做。。
            #region MyRegion


            builder.Configure(app =>
            {
                app.Use(next =>
                {
                    Console.WriteLine("This is CustomHostingStartup-Middleware  Init");
                    return(new RequestDelegate(
                               async context =>
                    {
                        Console.WriteLine("This is CustomHostingStartup-Middleware start");
                        await next.Invoke(context);
                        Console.WriteLine("This is CustomHostingStartup-Middleware end");
                    }));
                });
            });//甚至来个中间件
            #endregion
        }