Пример #1
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);

            var pathBase = Configuration["PATH_BASE"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
                app.UsePathBase(pathBase);
            }

#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            app.Map("/liveness", lapp => lapp.Run(async ctx => ctx.Response.StatusCode = 200));
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

            app.UseCors("CorsPolicy");

            ConfigureAuth(app);

            app.UseMvcWithDefaultRoute();

            app.UseSwagger()
            .UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Ordering.API V1");
                c.OAuthClientId("orderingswaggerui");
                c.OAuthAppName("Ordering Swagger UI");
            });

            ConfigureEventBus(app);
        }
Пример #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            if (_environment.IsProduction() || _environment.IsStaging())
            {
                services.AddDbContext <ApplicationDbContext>(options =>
                                                             options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            }
            else
            {
                services.AddDbContext <ApplicationDbContext>(options =>
                                                             options.UseInMemoryDatabase("LocalDb"));
            }
            if (_environment.IsProduction())
            {
                _logger.AddAzureWebAppDiagnostics(
                    new AzureAppServicesDiagnosticsSettings
                {
                    OutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss zzz} [{Level}] {RequestId}-{SourceContext}: {Message}{NewLine}{Exception}"
                });
            }

            services.Configure <IISOptions>(options =>
            {
            });

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = true;
                options.Password.RequiredLength         = 5;
                options.Password.RequireLowercase       = true;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
            });

            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();
            services.AddTransient <UserManager <ApplicationUser> >();
            services.AddTransient <DbInitializer>();
            services.AddTransient <OrderService>();
            services.AddTransient <DishService>();
            services.AddTransient <CategoryService>();
            services.AddTransient <UserService>();
            services.AddTransient <ManageOrderService>();
            services.AddTransient <PaymentService>();

            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout     = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
            });
            services.AddMvc();
        }
Пример #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider seriveProvider)
        {
            // Cors
            app.UseCors("AllowAll");

            // Authentication
            app.UseAuthentication();

            // Logging
            loggerFactory.AddAzureWebAppDiagnostics();
            app.SetHeavyDebugEnabled(Configuration.GetValue <bool>("Logging:HeavyDebugLogging"));

            // Business Logic
            app.UseServices(Configuration.GetConnectionString("DefaultConnection"),
                            Configuration["Authorization:OwnerEmail"]);

            // Socket Management
            app.UseSignalR(routes =>
            {
                routes.MapHub <DynamicHub>("deviceAddition");
            });

            // Static files setup for angular website
            if (Configuration.GetValue <bool>("Serving:ServeFrontend") || Configuration.GetValue <bool>("Serving:ServeSwagger"))
            {
                app.UseStaticFiles(new StaticFileOptions()
                {
                    FileProvider = new PhysicalFileProvider(
                        Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "dist")),
                    RequestPath = new PathString("")
                });
            }

            // Rewrite to Https if not running locally
            if (!this.Configuration.GetValue <bool>("Serving:IsDebug"))
            {
                var options = new RewriteOptions()
                              .AddRedirectToHttpsPermanent();

                app.UseRewriter(options);
            }

            if (Configuration.GetValue <bool>("Serving:ServeSwagger"))
            {
                // Enable middleware to serve generated Swagger as a JSON endpoint.
                app.UseSwagger();

                // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Trackable APIs V1");
                    c.ShowJsonEditor();
                    c.ShowRequestHeaders();
                    c.InjectOnCompleteJavaScript("/swagger/swagger.js");
                });
            }

            app.UseMvc();
        }
Пример #4
0
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            // Add the console logger.
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();

            // Configure error handling middleware.
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                // Enable middleware to serve generated Swagger as a JSON endpoint.
                //app.UseSwagger();
                //app.UseSwaggerUI(c =>
                //{
                //    c.SwaggerEndpoint("/swagger/v1/swagger.json", "ProposalManager  V1");
                //});
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            // Add CORS policies
            //app.UseCors("ExposeResponseHeaders");

            // Add static files to the request pipeline.
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            // Add session to the request pipeline
            app.UseSession();

            // Add authentication to the request pipeline
            app.UseAuthentication();

            // Configure MVC routes
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });

            app.UseMvc();
        }
Пример #5
0
        public static void ConfigureLogger(ILoggerFactory factory)
        {
            factory.AddConsole();
            factory.AddAzureWebAppDiagnostics();
            factory.AddDebug();

            LoggerFactory = factory;
        }
Пример #6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            var pathBase = Configuration["PATH_BASE"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
                app.UsePathBase(pathBase);
            }

            app.UseHealthChecks("/hc", new HealthCheckOptions()
            {
                Predicate      = _ => true,
                ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
            });

            app.UseHealthChecks("/liveness", new HealthCheckOptions
            {
                Predicate = r => r.Name.Contains("self")
            });

            app.UseStaticFiles();


            // Make work identity server redirections in Edge and lastest versions of browers. WARN: Not valid in a production environment.
            app.Use(async(context, next) =>
            {
                context.Response.Headers.Add("Content-Security-Policy", "script-src 'unsafe-inline'");
                await next();
            });

            app.UseForwardedHeaders();
            // Adds IdentityServer
            app.UseIdentityServer();

            app.UseHttpsRedirection();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            IConfiguration config        = null;
            LogLevel       level         = LogLevel.Critical;
            bool           includeScopes = false;
            Func <string, Microsoft.Extensions.Logging.LogLevel, bool> filter = null;

            Microsoft.Extensions.Logging.Console.IConsoleLoggerSettings consoleSettings = null;
            Microsoft.Extensions.Logging.AzureAppServices.AzureAppServicesDiagnosticsSettings azureSettings = null;
            Microsoft.Extensions.Logging.EventLog.EventLogSettings eventLogSettings = null;

            // An issue will be raised for each call to an ILoggerFactory extension methods adding loggers.
            loggerFactory.AddAzureWebAppDiagnostics();
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^    {{Make sure that this logger's configuration is safe.}}
            loggerFactory.AddAzureWebAppDiagnostics(azureSettings); // Noncompliant
            loggerFactory.AddConsole();                             // Noncompliant
            loggerFactory.AddConsole(level);                        // Noncompliant
            loggerFactory.AddConsole(level, includeScopes);         // Noncompliant
            loggerFactory.AddConsole(filter);                       // Noncompliant
            loggerFactory.AddConsole(filter, includeScopes);        // Noncompliant
            loggerFactory.AddConsole(config);                       // Noncompliant
            loggerFactory.AddConsole(consoleSettings);              // Noncompliant
            loggerFactory.AddDebug();                               // Noncompliant
            loggerFactory.AddDebug(level);                          // Noncompliant
            loggerFactory.AddDebug(filter);                         // Noncompliant
            loggerFactory.AddEventLog();                            // Noncompliant
            loggerFactory.AddEventLog(eventLogSettings);            // Noncompliant
            loggerFactory.AddEventLog(level);                       // Noncompliant
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^    {{Make sure that this logger's configuration is safe.}}

            // Testing the next method using a hack - see notes at the end of the file
            loggerFactory.AddEventSourceLogger(); // Noncompliant

            IEnumerable <ILoggerProvider>         providers      = null;
            LoggerFilterOptions                   filterOptions1 = null;
            IOptionsMonitor <LoggerFilterOptions> filterOptions2 = null;

            LoggerFactory factory = new LoggerFactory(); // Noncompliant

//                                  ^^^^^^^^^^^^^^^^^^^    {{Make sure that this logger's configuration is safe.}}

            new LoggerFactory(providers);                 // Noncompliant
            new LoggerFactory(providers, filterOptions1); // Noncompliant
            new LoggerFactory(providers, filterOptions2); // Noncompliant
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();

            app.UseMvc();
            this.ConfigureEventBus(app);
        }
Пример #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IAntiforgery antiforgery)
        {
            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);

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

            // Configure XSRF middleware, This pattern is for SPA style applications where XSRF token is added on Index page
            // load and passed back token on every subsequent async request
            // app.Use(async (context, next) =>
            // {
            //     if (string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase))
            //     {
            //         var tokens = antiforgery.GetAndStoreTokens(context);
            //         context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });
            //     }
            //     await next.Invoke();
            // });

            //Seed Data
            WebContextSeed.Seed(app, env, loggerFactory);

            var pathBase = Configuration["PATH_BASE"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
                app.UsePathBase(pathBase);
            }


#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            app.Map("/liveness", lapp => lapp.Run(async ctx => ctx.Response.StatusCode = 200));
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

            app.Use(async(context, next) =>
            {
                await next();

                // If there's no available file and the request doesn't contain an extension, we're probably trying to access a page.
                // Rewrite request to use app root
                if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value) && !context.Request.Path.Value.StartsWith("/api"))
                {
                    context.Request.Path        = "/index.html";
                    context.Response.StatusCode = 200; // Make sure we update the status code, otherwise it returns 404
                    await next();
                }
            });

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseMvcWithDefaultRoute();
        }
Пример #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            var pathBase = Configuration["PATH_BASE"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
                app.UsePathBase(pathBase);
            }


#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            app.Map("/liveness", lapp => lapp.Run(async ctx => ctx.Response.StatusCode = 200));
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

            app.UseSession();
            app.UseStaticFiles();

            if (Configuration.GetValue <bool>("UseLoadTest"))
            {
                app.UseMiddleware <ByPassAuthMiddleware>();
            }

            app.UseAuthentication();

            var log = loggerFactory.CreateLogger("identity");

            WebContextSeed.Seed(app, env, loggerFactory);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Catalog}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "defaultError",
                    template: "{controller=Error}/{action=Error}");
            });
        }
Пример #11
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            var pathBase = Configuration["PATH_BASE"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
                app.UsePathBase(pathBase);
            }

            app.UseSession();
            app.UseStaticFiles();
            app.UseKendo(env);

            if (Configuration.GetValue <bool>("UseLoadTest"))
            {
                app.UseMiddleware <ByPassAuthMiddleware>();
            }

            app.UseAuthentication();

            var log = loggerFactory.CreateLogger("identity");

            WebContextSeed.Seed(app, env, loggerFactory);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areaRoute",
                    template: "{area:exists}/{controller}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "defaultError",
                    template: "{controller=Error}/{action=Error}");
            });
        }
Пример #12
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="provider"></param>
        /// <param name="loggerFactory"></param>
        /// <param name="appLifetime"></param>
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              IApiVersionDescriptionProvider provider,
                              ILoggerFactory loggerFactory,
                              IApplicationLifetime appLifetime)
        {
            #region logging and exception
            if (!env.IsProduction())
            {
                loggerFactory.AddSerilog();
                // Ensure any buffered events are sent at shutdown
                appLifetime.ApplicationStopped.Register(Log.CloseAndFlush);

                loggerFactory.AddFile(Configuration.GetSection("Logging:Serilog"));
            }
            else
            {
                loggerFactory.AddAzureWebAppDiagnostics();
            }

            if (env.IsDevelopment())
            {
                loggerFactory.AddConsole();
                loggerFactory.AddDebug();
            }
            #endregion

            #region swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                foreach (var description in provider.ApiVersionDescriptions)
                {
                    c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json",
                                      description.GroupName.ToUpperInvariant());
                }
                c.DefaultModelRendering(ModelRendering.Model);
                c.DisplayOperationId();
                c.DisplayRequestDuration();
                c.DocExpansion(DocExpansion.None);
                c.EnableDeepLinking();
                c.ShowExtensions();
            });
            #endregion

            #region Middle-ware
            // add middle-ware
            app.UseMiddleware <LogResponseMiddleware>();
            app.UseMiddleware <LogRequestMiddleware>();

            app.UseMiddleware <ErrorWrappingMiddleware>();

            #endregion

            app.UseMvc();
        }
Пример #13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory)
        {
            //CREAMOS NUESTRO PROVEEDOR PARA EL LOGGER
            //loggerfactory.AddProvider(new ConsoleLoggerProvider(
            //    (categoria, nivel) => nivel >= LogLevel.Information, false)
            //    );

            ////PODEMOS CREAR DE FORMA EXPLICITA UN LOGGER
            //ILogger log = loggerfactory.CreateLogger<ConsoleLogger>();

            ////MOSTRAMOS MENSAJES
            //log.LogInformation("Mensaje desde StartUp Configuration");

            loggerfactory.AddAzureWebAppDiagnostics(
                new AzureAppServicesDiagnosticsSettings
            {
                OutputTemplate = "{Timestamp:dd-MM-yyyy HH:mm:ss zzz} [{Level}] {RequestId}-{SourceContext}: {Message}{NewLine}{Exception}"
            }
                );

            Trace.Listeners.Add(new ApplicationInsightsTraceListener());


            //1. CONTROL DE ERRORES
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //4. UTILIZAMOS ARCHIVOS DE wwwroot
            app.UseStaticFiles();

            //5. POLITICA DE COOKIES
            app.UseCookiePolicy();

            //7. UTILIZAMOS LA SESION
            app.UseSession();


            //8. DEBEMOS DAR LA RUTA DE INICIO
            //CONFIGURAMOS LAS AREAS
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=RealMadrid}/{action=Index}/{id?}"
                    );
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Пример #14
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();

            app.UseMiddleware(typeof(InMiddleware));

            app.UseMvc();
        }
Пример #15
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddAzureWebAppDiagnostics();

            //app.UseDeveloperExceptionPage();
            var options = new RewriteOptions()
                          //.AddRedirectToHttps()
            ;

            app.UseRewriter(options);

            app.UseExceptionHandler().WithConventions(x =>
            {
                x.ContentType = "application/json";
                x.MessageFormatter(s => JsonConvert.SerializeObject(new
                {
                    Message = "An error occurred whilst processing your request"
                }));

                x.ForException <UnauthorizedAccessException>()
                .ReturnStatusCode((int)HttpStatusCode.Unauthorized)
                .UsingMessageFormatter((ex, context) => JsonConvert.SerializeObject(new
                {
                    Message = "Unauthorized Access"
                }));

                x.ForException <WebMessageException>()
                .ReturnStatusCode((int)HttpStatusCode.OK)
                .UsingMessageFormatter((ex, context) =>
                {
                    context.Response.StatusCode = ((WebMessageException)ex).StatusCode;

                    return(JsonConvert.SerializeObject(new
                    {
                        Message = ex.Message,
                    }));
                });

                x.OnError((exception, httpContext) =>
                {
                    _logger.LogError(exception.Message);

                    TelemetryClient telemetryClient = new TelemetryClient();

                    telemetryClient.TrackException(exception);

                    return(Task.CompletedTask);
                });
            });

            app.UseIdentityServer();

            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
Пример #16
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);

            var pbase = Configuration["PATH_BASE"];

            if (!string.IsNullOrEmpty(pbase))
            {
                app.UsePathBase(pbase);
            }

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

            app.UseCors(builder =>
            {
                builder
                .AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod();
            });
            app.UseStaticFiles();
            app.UseByPassAuth();
            app.UseAuthentication();


            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                var b2cConfig = Configuration.GetSection("b2c");
                var path      = string.IsNullOrEmpty(pbase) || pbase == "/" ? "/" : $"{pbase}/";
                c.InjectOnCompleteJavaScript($"{path}swagger-ui-b2c.js");
                c.SwaggerEndpoint($"{path}swagger/v1/swagger.json", "Hotels Api");
                c.ConfigureOAuth2(b2cConfig["ClientId"], "y", "z", "z", "",
                                  new
                {
                    p      = "B2C_1_SignUpInPolicy",
                    prompt = "login",
                    nonce  = "defaultNonce"
                });
            });

            app.UseSignalR(routes =>
            {
                routes.MapHub <ChatHub>("/chatHub");
            });
            app.UseMvc();
        }
Пример #17
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();

            //Middleware.
            app.UseOAuthValidation();
            app.UseOpenIddict();
            app.UseMvc();
        }
Пример #18
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (!env.IsDevelopment())
            {
                loggerFactory.AddAzureWebAppDiagnostics();
                loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);
            }

            app.UseAuthentication();
            app.UseMvc();
        }
Пример #19
0
        // Этот метод вызывается во время выполнения. Используется для настройки конвейера HTTP-запросов.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              IServiceProvider serviceProvider, ILoggerFactory loggerFactory)
        {
            // Настройка фабрики логов
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);

            // Базовый путь, если есть
            var pbase = Configuration["PATH_BASE"];

            if (!string.IsNullOrEmpty(pbase))
            {
                app.UsePathBase(pbase);
            }

            // Добавляем использование кросс доменных запросов (Cross Origin Resource Sharing)
            // Для запросов из приложения с одного адреса (или домена) к приложению, которое размещено по другому адресу
            app.UseCors(builder => {
                builder
                .AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod();
            });

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

            app.UseStaticFiles();
            app.UseByPassAuth();
            app.UseAuthentication();

            // Настройка использования Swagger UI
            app.UseSwagger();
            app.UseSwaggerUI(c => {
                var path = string.IsNullOrEmpty(pbase) || pbase == "/" ? "/" : $"{pbase}/";

                c.InjectOnCompleteJavaScript($"{path}swagger-ui-b2c.js");
                c.SwaggerEndpoint($"{path}swagger/v1/swagger.json", "Bookings Api");
                // AAD B2C
                var b2cConfig = Configuration.GetSection("b2c");
                c.ConfigureOAuth2(b2cConfig["ClientId"], "y", "z", "z", "",
                                  new {
                    p      = "B2C_1_SignUpInPolicy",
                    prompt = "login",
                    nonce  = "defaultNonce"
                });
            });

            app.UseMvc();
        } // Configure
Пример #20
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();

            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);

            var pathBase = Configuration["PATH_BASE"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                app.UsePathBase(pathBase);
            }

            app.UseHealthChecks("/hc", new HealthCheckOptions()
            {
                Predicate      = _ => true,
                ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
            });

            app.UseHealthChecks("/liveness", new HealthCheckOptions
            {
                Predicate = r => r.Name.Contains("self")
            });

            app.UseStaticFiles();
            app.UseCors("CorsPolicy");

            ConfigureAuth(app);

            app.UseMvcWithDefaultRoute();

            app.UseSwagger()
            .UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Customer.API V1");
                c.OAuthClientId("customerswaggerui");
                c.OAuthAppName("Customer Swagger UI");
            });

            ConfigureEventBus(app);
            ConfigureMicroservice(env);
        }
Пример #21
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Error);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            var pathBase = Configuration["PATH_BASE"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
                app.UsePathBase(pathBase);
            }


#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            app.Map("/liveness", lapp => lapp.Run(async ctx => ctx.Response.StatusCode = 200));
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

            app.UseStaticFiles();


            // Make work identity server redirections in Edge and lastest versions of browers. WARN: Not valid in a production environment.
            app.Use(async(context, next) =>
            {
                context.Response.Headers.Add("Content-Security-Policy", "script-src 'unsafe-inline'");
                await next();
            });


            app.UseForwardedHeaders();
            // Adds IdentityServer
            app.UseIdentityServer();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "ApiByAppId",
                    template: "{appId}/{controller=Home}/{action=Index}/{id?}");
            });
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);

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

            app.UseCors("CorsPolicy");
            app.UseMvc();
        }
Пример #24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SayonaraContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            // Configure the OWIN pipeline to use cookie auth.
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            //Allows the workers to authenticate using Azure AD bearer tokens
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                Audience              = Configuration["AzureAd:Audience"],
                Authority             = "https://login.microsoftonline.com/nethealth.com",
                AutomaticAuthenticate = true
            });

            // Configure the OWIN pipeline to use OpenID Connect auth.
            app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
            {
                Authority             = "https://login.microsoftonline.com/nethealth.com",
                ClientId              = Configuration["AzureAD:ClientId"],
                PostLogoutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"],
                ResponseType          = OpenIdConnectResponseType.IdToken,
                Events = new OpenIdConnectEvents
                {
                    OnRemoteFailure = OnAuthenticationFailed,
                }
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            SayonaraDBInitialize.Initialize(context);
        }
Пример #25
0
        /// <summary>
        /// Configure web application.
        /// </summary>
        /// <param name="app">Application builder.</param>
        /// <param name="env">Environment parameters.</param>
        /// <param name="loggerFactory">Logger.</param>
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory
            )
        {
            if (env.IsDevelopment())
            {
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();
            }
            else
            {
                loggerFactory.AddAzureWebAppDiagnostics();
            }

            var uploadServerOptions = new BackgroundJobServerOptions
            {
                Queues      = new [] { "upload" },
                WorkerCount = 1
            };

            app.UseHangfireServer(uploadServerOptions);

            if (UseServiceDiscovery)
            {
                var defaultServerOptions = new BackgroundJobServerOptions
                {
                    Queues = new [] { "default" }
                };

                app.UseHangfireServer(defaultServerOptions);
                RecurringJob.AddOrUpdate <IServiceDiscoveryRegistrationJob>("register-service", x => x.RegisterServiceAsync(null), Cron.Minutely);
            }

            app.UseErrorHandler();

            app.UseCors("AllowAllOrigins");

            app.UseRewriteAccessTokenFronQueryToHeader();

            app.UseAuthentication();

            app.UseMvc();

            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1");
            });
        }
Пример #26
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);

            var pathBase = Configuration["PATH_BASE"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                app.UsePathBase(pathBase);
            }

            ConfigureEventBus(app);
        }
Пример #27
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //Configure logs

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);

            var pathBase = Configuration["PATH_BASE"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
                app.UsePathBase(pathBase);
            }


            /// set up Zipkin tracing services
            var applicationName = Configuration["applicationName"];
            var lifetime        = app.ApplicationServices.GetService <IApplicationLifetime>();

            lifetime.ApplicationStarted.Register(() => {
                TraceManager.SamplingRate = 1.0f;
                var logger     = new TracingLogger(loggerFactory, "zipkin4net");
                var httpSender = new HttpZipkinSender("http://localhost:9411", "application/json");
                var stats      = new Statistics();
                var tracer     = new ZipkinTracer(httpSender, new JSONSpanSerializer(), stats);
                TraceManager.RegisterTracer(tracer);
                TraceManager.Start(logger);
            });
            lifetime.ApplicationStopped.Register(() => TraceManager.Stop());
            app.UseTracing(applicationName);

#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            app.Map("/liveness", lapp => lapp.Run(async ctx => ctx.Response.StatusCode = 200));
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

            app.UseCors("CorsPolicy");

            app.UseMvcWithDefaultRoute();

            app.UseSwagger()
            .UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Catalog.API V1");
            });

            ConfigureEventBus(app);
        }
Пример #28
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();

            app.UseCookieAuthentication();

            app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
            {
                ClientId     = Configuration["AzureAd:ClientId"],
                Authority    = string.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAd:TenantId"]),
                CallbackPath = Configuration["AzureAd:AuthCallback"]
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.Use(async(context, next) =>
                {
                    if (context.Request.IsHttps)
                    {
                        await next();
                    }
                    else
                    {
                        var withHttps = "https://" + context.Request.Host + context.Request.Path;
                        context.Response.Redirect(withHttps);
                    }
                });
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseSwagger();
            app.UseSwaggerUi();
        }
Пример #29
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, Context context)
        {
            loggerFactory.AddDebug(LogLevel.Critical);
            loggerFactory.AddAzureWebAppDiagnostics();

            Mapper.Initialize(config =>
            {
                config.CreateMap <Group, GroupViewModel>();
            });

            //context.Database.Migrate();

            //app.Use(async (webContext, next) =>
            //{
            //  if (webContext.Request.IsHttps)
            //  {
            //    await next();
            //  }
            //  else
            //  {
            //    //same as what's used for blizz redirect so let's be lazy :P
            //    var httpsUrl = _config.GetSection("BlizzRedirect").Value;
            //    webContext.Response.Redirect(httpsUrl);
            //  }
            //});

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

            app.UseBrowserLink();

            app.UseWebSockets();

            app.UseSignalR();

            app.UseStaticFiles();

            app.UseIdentity();

            app.UseMvc(config =>
            {
                config.MapRoute(
                    name: "default",
                    template: "{controller=home}/{action=index}/{id?}"
                    );
            });
        }
Пример #30
0
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
         loggerFactory.AddDebug();
     }
     app.UseMvc();
     loggerFactory.AddAzureWebAppDiagnostics(
         new Microsoft.Extensions.Logging.AzureAppServices.AzureAppServicesDiagnosticsSettings
     {
         OutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss zz [{Level}] {RequestId}-{SourceContext}: {Message}{ NewLine}{ Exception}"
     }
         );
 }