コード例 #1
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup <Startup>();

            webBuilder.ConfigureAppConfiguration((ctx, cb) =>
            {
                if (!ctx.HostingEnvironment.IsDevelopment())
                {
                    StaticWebAssetsLoader.UseStaticWebAssets(ctx.HostingEnvironment, ctx.Configuration);
                }
            });
        });
コード例 #2
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseUrls("http://localhost:6000");         // Configure on port 6000 instead of default
            webBuilder.UseStartup <Startup>();

            // 👇 Add this "ConfigureAppConfiguration" method calling.
            webBuilder.ConfigureAppConfiguration((ctx, cb) =>
            {
                // 👇 This call inserts "StaticWebAssetsFileProvider" into
                //    the static file middleware.
                StaticWebAssetsLoader.UseStaticWebAssets(
                    ctx.HostingEnvironment,
                    ctx.Configuration);
            });
        });
コード例 #3
0
        public DefaultWebHostConfiguration ConfigureRouting()
        {
#if NETCOREAPP3_0 || NETCOREAPP3_1
            _builder.ConfigureAppConfiguration((WebHostBuilderContext hostingContext, IConfigurationBuilder _) =>
            {
                if (hostingContext.HostingEnvironment.IsDevelopment())
                {
                    StaticWebAssetsLoader.UseStaticWebAssets(hostingContext.HostingEnvironment, hostingContext.Configuration);
                }
            });
#endif

            _builder.ConfigureServices((WebHostBuilderContext hostingContext, IServiceCollection services) =>
            {
                services.AddRouting();
            });

            return(this);
        }
コード例 #4
0
        public void ResolveManifest_ManifestFromFile()
        {
            // Arrange
            var expectedManifest = @"<StaticWebAssets Version=""1.0"">
  <ContentRoot Path=""/Path"" BasePath=""/BasePath"" />
</StaticWebAssets>
";

            var environment = new HostingEnvironment()
            {
                ApplicationName = "Microsoft.AspNetCore.TestHost"
            };

            // Act
            var manifest = StaticWebAssetsLoader.ResolveManifest(environment);

            // Assert
            Assert.Equal(expectedManifest, new StreamReader(manifest).ReadToEnd());
        }
コード例 #5
0
        public void ResolveManifest_FindsEmbeddedManifestProvider()
        {
            // Arrange
            var expectedManifest = @"<StaticWebAssets Version=""1.0"">
  <ContentRoot Path=""/Path"" BasePath=""/BasePath"" />
</StaticWebAssets>
";
            var originalRoot     = new NullFileProvider();
            var environment      = new HostingEnvironment()
            {
                ApplicationName = typeof(StaticWebAssetsReaderTests).Assembly.GetName().Name
            };

            // Act
            var manifest = StaticWebAssetsLoader.ResolveManifest(environment);

            // Assert
            Assert.Equal(expectedManifest, new StreamReader(manifest).ReadToEnd());
        }
コード例 #6
0
        public void UseStaticWebAssetsCore_DoesNothing_WhenManifestDoesNotContainEntries()
        {
            // Arrange
            var manifestContent = @$ "<StaticWebAssets Version=" "1.0" ">
</StaticWebAssets>";

            var manifest     = CreateManifest(manifestContent);
            var originalRoot = new NullFileProvider();
            var environment  = new HostingEnvironment()
            {
                WebRootFileProvider = originalRoot
            };

            // Act
            StaticWebAssetsLoader.UseStaticWebAssetsCore(environment, manifest);

            // Assert
            Assert.Equal(originalRoot, environment.WebRootFileProvider);
        }
コード例 #7
0
        public void UseStaticWebAssetsCore_CreatesCompositeRoot_WhenThereAreContentRootsInTheManifest()
        {
            // Arrange
            var manifestContent = @$ "<StaticWebAssets Version=" "1.0" ">
    <ContentRoot Path=" "{AppContext.BaseDirectory}" " BasePath=" "/BasePath" " />
</StaticWebAssets>";

            var manifest     = CreateManifest(manifestContent);
            var originalRoot = new NullFileProvider();
            var environment  = new HostingEnvironment()
            {
                WebRootFileProvider = originalRoot
            };

            // Act
            StaticWebAssetsLoader.UseStaticWebAssetsCore(environment, manifest);

            // Assert
            var composite = Assert.IsType <CompositeFileProvider>(environment.WebRootFileProvider);

            Assert.Equal(2, composite.FileProviders.Count());
            Assert.Equal(originalRoot, composite.FileProviders.First());
        }
コード例 #8
0
ファイル: Startup.cs プロジェクト: mgzam/DigitalLife
        public void Configure(IApplicationBuilder app, ILogger <Startup> log)
        {
            Log = log;

            // This server serves static content from Blazor Client,
            // and since we don't copy it to local wwwroot,
            // we need to find Client's wwwroot in bin/(Debug/Release) folder
            // and set it as this server's content root.
            var baseDir     = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "";
            var binCfgPart  = Regex.Match(baseDir, @"[\\/]bin[\\/]\w+[\\/]").Value;
            var wwwRootPath = Path.Combine(baseDir, "wwwroot");

            if (!Directory.Exists(Path.Combine(wwwRootPath, "_framework")))
            {
                // This is a regular build, not a build produced w/ "publish",
                // so we remap wwwroot to the client's wwwroot folder
                wwwRootPath = Path.GetFullPath(Path.Combine(baseDir, $"../../../../UI/{binCfgPart}/net5.0/wwwroot"));
            }
            Env.WebRootPath         = wwwRootPath;
            Env.WebRootFileProvider = new PhysicalFileProvider(Env.WebRootPath);
            StaticWebAssetsLoader.UseStaticWebAssets(Env, Cfg);

            if (Env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();

            var provider = new FileExtensionContentTypeProvider();

            provider.Mappings.Add(".dae", "text/xml");
            provider.Mappings.Add(".glb", "text/xml");
            provider.Mappings.Add(".fbx", "text/xml");
            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = provider
            });


            app.UseWebSockets(new WebSocketOptions()
            {
                KeepAliveInterval = TimeSpan.FromSeconds(30),
            });
            app.UseFusionSession();

            // Static + Swagger
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();
            app.UseSwagger();
            app.UseSwaggerUI(c => {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1");
            });

            // API controllers
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => {
                endpoints.MapBlazorHub();
                endpoints.MapFusionWebSocketServer();
                endpoints.MapControllers();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
コード例 #9
0
        private static IHostBuilder CreateHostBuilder(string[] args)
        {
            return(new HostBuilder()
                   .UseContentRoot(Directory.GetCurrentDirectory())
                   .ConfigureAppConfiguration((context, builder) =>
            {
                var env = context.HostingEnvironment;

                builder.AddJsonFile("appsettings.json", false, false)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true)
                .AddEnvironmentVariables()
                .AddCommandLine(args);

                context.Configuration = builder.Build();
            })
                   .ConfigureLogging((_, builder) =>
            {
                builder.ClearProviders();

                if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME")))
                {
                    var loggerBuilder = new LoggerConfiguration()
                                        .Enrich.FromLogContext()
                                        .MinimumLevel.Information();

                    loggerBuilder.Enrich.WithMachineName()
                    .Enrich.WithEnvironmentName()
                    .MinimumLevel.Debug()
                    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                    .MinimumLevel.Override("System", LogEventLevel.Warning)
                    .WriteTo.Console(outputTemplate:
                                     "[{Timestamp:HH:mm:ss} {Level} {EnvironmentName}-{MachineName}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}",
                                     theme: AnsiConsoleTheme.Literate);

                    builder.AddSerilog(loggerBuilder.CreateLogger());
                }

                builder.AddApplicationInsights(options =>
                {
                    options.IncludeScopes = true;
                    options.FlushOnDispose = true;
                });

                builder.AddFilter <ApplicationInsightsLoggerProvider>("", LogLevel.Debug);
                builder.AddFilter <ApplicationInsightsLoggerProvider>("Microsoft", LogLevel.Warning);
                builder.AddFilter <ApplicationInsightsLoggerProvider>("System", LogLevel.Warning);
            })
                   .UseDefaultServiceProvider((context, options) =>
            {
                var isDevelopment = context.HostingEnvironment.IsDevelopment();
                options.ValidateScopes = isDevelopment;
                options.ValidateOnBuild = isDevelopment;
            })
                   .ConfigureServices((_, services) => { services.AddOptions(); })
                   .ConfigureWebHost(builder =>
            {
                builder.ConfigureAppConfiguration((ctx, cb) =>
                {
                    if (ctx.HostingEnvironment.IsDevelopment())
                    {
                        StaticWebAssetsLoader.UseStaticWebAssets(ctx.HostingEnvironment, ctx.Configuration);
                    }
                });
                builder.UseContentRoot(Directory.GetCurrentDirectory());
                builder.UseKestrel((context, options) => { options.Configure(context.Configuration.GetSection("Kestrel")); });
                builder.UseIIS();
                builder.UseStartup <Startup>();
            }));
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: ise621/database
 // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host
 public static IHostBuilder CreateHostBuilder(
     string[] commandLineArguments
     )
 {
     return(new HostBuilder()
            .UseContentRoot(
                Directory.GetCurrentDirectory()
                )
            // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host#host-configuration
            .ConfigureHostConfiguration(configuration =>
     {
         configuration.AddEnvironmentVariables(prefix: "DOTNET_");
         configuration.AddCommandLine(commandLineArguments);
     }
                                        )
            // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/
            .ConfigureAppConfiguration((hostingContext, configuration) =>
                                       ConfigureAppConfiguration(
                                           configuration,
                                           hostingContext.HostingEnvironment,
                                           commandLineArguments
                                           )
                                       )
            // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/
            .ConfigureLogging((_, loggingBuilder) =>
     {
         loggingBuilder.Configure(options =>
         {
             options.ActivityTrackingOptions = ActivityTrackingOptions.SpanId
                                               | ActivityTrackingOptions.TraceId
                                               | ActivityTrackingOptions.ParentId;
         });
     })
            // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection
            .UseDefaultServiceProvider((context, options) =>
     {
         var isDevelopment = context.HostingEnvironment.IsDevelopment();
         options.ValidateScopes = isDevelopment;
         options.ValidateOnBuild = isDevelopment;
     })
            .UseSerilog((webHostBuilderContext, loggerConfiguration) =>
     {
         ConfigureLogging(
             loggerConfiguration,
             webHostBuilderContext.HostingEnvironment.EnvironmentName
             );
         loggerConfiguration
         .ReadFrom.Configuration(webHostBuilderContext.Configuration);
     }
                        )
            // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host
            // https://github.com/dotnet/aspnetcore/blob/main/src/DefaultBuilder/src/WebHost.cs#L215
            .ConfigureWebHost(_ =>
                              _
                              .ConfigureAppConfiguration((context, _) =>
     {
         if (context.HostingEnvironment.IsDevelopment())
         {
             StaticWebAssetsLoader.UseStaticWebAssets(context.HostingEnvironment, context.Configuration);
         }
     })
                              // Default web server https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel
                              .UseKestrel((context, options) =>
                                          options.Configure(context.Configuration.GetSection("Kestrel"), reloadOnChange: true)
                                          )
                              .ConfigureServices((context, services) =>
     {
         // Fallback
         // services.PostConfigure<HostFilteringOptions>(options =>
         // {
         //     if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)
         //     {
         //         // "AllowedHosts": "localhost;127.0.0.1;[::1]"
         //         var hosts = context.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
         //         // Fall back to "*" to disable.
         //         options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
         //     }
         // });
         // Change notification
         // services.AddSingleton<IOptionsChangeTokenSource<HostFilteringOptions>>(
         //     new ConfigurationChangeTokenSource<HostFilteringOptions>(context.Configuration));
         // services.AddTransient<IStartupFilter, HostFilteringStartupFilter>();
         services.AddRouting();
     })
                              // .UseIIS()
                              // .UseIISIntegration()
                              .UseStartup <Startup>()
                              ));
 }