示例#1
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app">Defines a class that provides the mechanisms to configure an application's request pipeline.</param>
        public void Configure(IApplicationBuilder app)
        {
            if (HostingEnvironment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.IdentityServerStoreSetup <ExtendedConfigurationDbContext>(Clients.Get(), Resources.GetIdentityResources(), Resources.GetApiResources());
            }
            else
            {
                app.UseHsts();
                app.UseHttpsRedirection();
            }
            app.UseStaticFiles(new StaticFileOptions {
                OnPrepareResponse = context => {
                    const int durationInSeconds = 60 * 60 * 24;
                    context.Context.Response.Headers[HeaderNames.CacheControl] = $"public,max-age={durationInSeconds}";
                    context.Context.Response.Headers.Append(HeaderNames.Expires, DateTime.UtcNow.AddSeconds(durationInSeconds).ToString("R", CultureInfo.InvariantCulture));
                }
            });
            app.UseCookiePolicy();
            app.UseRouting();
            app.UseIdentityServer();
            app.UseCors();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"), branch => {
                if (!HostingEnvironment.IsDevelopment())
                {
                    branch.UseExceptionHandler("/error");
                }
            });
            app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), branch => {
                branch.UseProblemDetails();
            });
            app.UseRequestLocalization(new RequestLocalizationOptions {
                DefaultRequestCulture   = new RequestCulture(SupportedCultures.Default),
                RequestCultureProviders = new List <IRequestCultureProvider> {
                    new QueryStringRequestCultureProvider(),
                    new CookieRequestCultureProvider()
                },
                SupportedCultures   = SupportedCultures.Get().ToList(),
                SupportedUICultures = SupportedCultures.Get().ToList()
            });
            app.UseResponseCaching();
            app.UseSwagger();
            var enableSwagger = HostingEnvironment.IsDevelopment() || Configuration.GetValue <bool>($"{GeneralSettings.Name}:SwaggerUI");

            if (enableSwagger)
            {
                app.UseSwaggerUI(swaggerOptions => {
                    swaggerOptions.RoutePrefix = "docs";
                    swaggerOptions.SwaggerEndpoint($"/swagger/{IdentityServerApi.Scope}/swagger.json", IdentityServerApi.Scope);
                    swaggerOptions.OAuth2RedirectUrl($"{Settings.Host}/docs/oauth2-redirect.html");
                    swaggerOptions.OAuthClientId("swagger-ui");
                    swaggerOptions.OAuthAppName("Swagger UI");
                    swaggerOptions.DocExpansion(DocExpansion.None);
                });
            }
            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
            });
            if (!HostingEnvironment.IsDevelopment())
            {
                app.UseSpaStaticFiles();
                app.UseSpa(builder => {
                    builder.Options.SourcePath = "wwwroot/admin-ui";
                });
            }
        }
示例#2
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app">Defines a class that provides the mechanisms to configure an application's request pipeline.</param>
        public void Configure(IApplicationBuilder app)
        {
            if (HostingEnvironment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.IdentityServerStoreSetup <ExtendedConfigurationDbContext>(Clients.Get(), Resources.GetIdentityResources(), Resources.GetApis(), Resources.GetApiScopes());
            }
            else
            {
                app.UseHsts();
                app.UseHttpsRedirection();
            }
            var staticFileOptions = new StaticFileOptions {
                OnPrepareResponse = context => {
                    const int durationInSeconds = 60 * 60 * 24;
                    context.Context.Response.Headers[HeaderNames.CacheControl] = $"public,max-age={durationInSeconds}";
                    context.Context.Response.Headers.Append(HeaderNames.Expires, DateTime.UtcNow.AddSeconds(durationInSeconds).ToString("R", CultureInfo.InvariantCulture));
                }
            };

            app.UseStaticFiles(staticFileOptions);
            app.UseCookiePolicy();
            app.UseRouting();
            // Use the middleware with parameters to log request responses to the ILogger or use custom parameters to lets say take request response snapshots for testing purposes.
            //app.UseRequestResponseLogging(
            //    new[] { System.Net.Mime.MediaTypeNames.Application.Json, System.Net.Mime.MediaTypeNames.Text.Html }, async (logger, model) => {
            //        var filename = $"{model.RequestTime:yyyyMMdd.HHmmss}_{model.RequestTarget.Replace('/', '-')}_{model.StatusCode}";
            //        var folder = System.IO.Path.Combine(HostingEnvironment.ContentRootPath, @"App_Data\snapshots");
            //        if (System.IO.Directory.Exists(folder)) {
            //            System.IO.Directory.CreateDirectory(folder);
            //        }
            //        if (!string.IsNullOrEmpty(model.RequestBody)) {
            //            await System.IO.File.WriteAllTextAsync(System.IO.Path.Combine(folder, $"{filename}_request.txt"), model.RequestBody);
            //        }
            //        await System.IO.File.WriteAllTextAsync(System.IO.Path.Combine(folder, $"{filename}_response.txt"), model.ResponseBody);
            //    }
            //);
            app.UseIdentityServer();
            app.UseCors();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"), branch => {
                if (!HostingEnvironment.IsDevelopment())
                {
                    branch.UseExceptionHandler("/error");
                }
            });
            app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), branch => {
                branch.UseProblemDetails();
            });
            app.UseRequestLocalization(new RequestLocalizationOptions {
                DefaultRequestCulture   = new RequestCulture(SupportedCultures.Default),
                RequestCultureProviders = new List <IRequestCultureProvider> {
                    new QueryStringRequestCultureProvider(),
                    new CookieRequestCultureProvider()
                },
                SupportedCultures   = SupportedCultures.Get().ToList(),
                SupportedUICultures = SupportedCultures.Get().ToList()
            });
            app.UseResponseCaching();
            app.UseSwagger();
            var enableSwagger = HostingEnvironment.IsDevelopment() || Configuration.GetValue <bool>($"{GeneralSettings.Name}:SwaggerUI");

            if (enableSwagger)
            {
                app.UseSwaggerUI(options => {
                    options.RoutePrefix = "docs";
                    options.SwaggerEndpoint($"/swagger/{IdentityServerApi.Scope}/swagger.json", IdentityServerApi.Scope);
                    options.OAuth2RedirectUrl($"{Settings.Host}/docs/oauth2-redirect.html");
                    options.OAuthClientId("swagger-ui");
                    options.OAuthAppName("Swagger UI");
                    options.DocExpansion(DocExpansion.None);
                    options.OAuthUsePkce();
                    options.OAuthScopeSeparator(" ");
                });
            }
            app.UseAdminUI(options => {
                options.Path              = "admin";
                options.ClientId          = "idsrv-admin-ui";
                options.DocumentTitle     = "Admin UI";
                options.Authority         = Settings.Authority;
                options.Host              = Settings.Host;
                options.Enabled           = true;
                options.OnPrepareResponse = staticFileOptions.OnPrepareResponse;
                options.InjectStylesheet("/css/admin-ui-overrides.css");
            });
            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
                endpoints.MapDefaultControllerRoute();
            });
        }