public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json"); Configuration = builder.Build(); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var builder = new ContainerBuilder(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>(); //app.UseCookieAuthentication(options => //{ // options.AuthenticationScheme = "Temp"; // options.AutomaticAuthentication = false; //}, "external"); // Configure the HTTP request pipeline. //app.UseStaticFiles(); // Add the following route for porting Web API 2 controllers. // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}"); app.UseOAuthBearerAuthentication(options => { options.Authority = "https://localhost:44333/core"; //options.Authority = "https://karamaidentityserver.azurewebsites.net/core"; options.Audience = "https://karama.com/resources"; options.AutomaticAuthentication = true; }); app.UseMiddleware<RequiredScopesMiddleware>(new List<string> { "api3" }); app.UseCors("AllowSpecificOrigins"); // Add MVC to the request pipeline. app.UseMvc(); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.MinimumLevel = LogLevel.Information; loggerFactory.AddConsole(); // Configure the HTTP request pipeline. // Add the following to the request pipeline only in development environment. if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseErrorPage(ErrorPageOptions.ShowAll); } else { // Add Error handling middleware which catches all application specific errors and // send the request to the following path or controller action. app.UseErrorHandler("/Home/Error"); } // Add static files to the request pipeline. app.UseStaticFiles(); // Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); // Uncomment the following line to add a route for porting Web API 2 controllers. // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}"); }); }
// Configure is called after ConfigureServices is called. public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, MyHealthDataInitializer dataInitializer) { loggerFactory.MinimumLevel = LogLevel.Information; loggerFactory.AddConsole(); loggerFactory.AddDebug(); // Configure the HTTP request pipeline. // Add the following to the request pipeline only in development environment. if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(options => options.EnableAll()); } else { // Add Error handling middleware which catches all application specific errors and // sends the request to the following path or controller action. app.UseExceptionHandler("/Home/Error"); } // Add the platform handler to the request pipeline. app.UseIISPlatformHandler(); // Add static files to the request pipeline. app.UseStaticFiles(); // Add MVC to the request pipeline. app.ConfigureRoutes(); await dataInitializer.InitializeDatabaseAsync(app.ApplicationServices, Configuration); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IConfigurationRoot configuration) { loggerFactory.AddConsole(configuration.GetSection("Logging")); loggerFactory.AddDebug(); // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859 try { using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>() .CreateScope()) { using (var db = serviceScope.ServiceProvider.GetService<ApplicationDbContext>()) { db.Database.EnsureCreated(); db.Database.Migrate(); } } } catch (Exception exception) { } app.UseCors("AllowAllOrigins"); // TODO: allow collection of allowed origins per client app.UseIISPlatformHandler(); app.UseStaticFiles(); app.UseMvc(); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory) { // Configure the HTTP request pipeline. // Add the console logger. loggerfactory.AddConsole(minLevel: LogLevel.Verbose); // Add the following to the request pipeline only in development environment. if (env.IsEnvironment("Development")) { app.UseBrowserLink(); app.UseErrorPage(ErrorPageOptions.ShowAll); } else { // Add Error handling middleware which catches all application specific errors and // send the request to the following path or controller action. app.UseErrorHandler("/Home/Error"); } // Add static files to the request pipeline. app.UseStaticFiles(); // Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); SampleData.Initialize(app.ApplicationServices); }
/// <summary> /// Configure default cookie settings for the application which are more secure by default. /// </summary> /// <param name="application">The application.</param> /// <param name="environment">The environment the application is running under. This can be Development, /// Staging or Production by default.</param> private static void ConfigureCookies( IApplicationBuilder application, IHostingEnvironment environment) { // In the Development environment, different ports are being used for HTTP and HTTPS. The // RequireHttpsAttribute expects to use the default ports 80 for HTTP and port 443 for HTTPS and simply // adds an 's' onto 'http'. Therefore, we don't require secure cookies in the development environment. SecurePolicy securePolicy; if (environment.IsDevelopment()) { // Ensure that the cookie can only be transported over the same scheme as the request. securePolicy = SecurePolicy.SameAsRequest; } else { // Ensure that the cookie can only be transported over HTTPS. securePolicy = SecurePolicy.Always; } application.UseCookiePolicy( new CookiePolicyOptions() { // Ensure that external script cannot access the cookie. HttpOnly = HttpOnlyPolicy.Always, Secure = securePolicy }); }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { var configPath = Path.Combine(appEnv.ApplicationBasePath, "..", ".."); Configuration = new Configuration(configPath).AddJsonFile("config.json"). AddEnvironmentVariables("SmsPrize_"); }
public Startup(IHostingEnvironment env) { // Setup configuration sources. Configuration = new Configuration() .AddJsonFile("config.json") .AddEnvironmentVariables(); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // Add MVC to the request pipeline. app.UseMvc(); // Add the following route for porting Web API 2 controllers. // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}"); }
public XmlBlogRepository(IHostingEnvironment env, IMemoryCache memoryCache, ILoggerFactory loggerFactory) : base(env, memoryCache) { Logger = loggerFactory.CreateLogger<XmlBlogRepository>(); }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath) .AddJsonFile("config.json") .AddEnvironmentVariables(); Configuration = builder.Build(); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.MinimumLevel = LogLevel.Information; // Add the following to the request pipeline only in development environment. if (env.IsDevelopment()) { app.UseBrowserLink(); //app.UseErrorPage(ErrorPageOptions.ShowAll); } else { // Add Error handling middleware which catches all application specific errors and // sends the request to the following path or controller action. //app.UseErrorHandler("/Home/Error"); } // Add static files to the request pipeline. app.UseStaticFiles(); // Add MVC to the request pipeline. app.UseMvc(routes => { }); app.UseMvc(); }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { // Setup configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsEnvironment("Development")) { // This reads the configuration keys from the secret store. // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets(); } // this file name is ignored by gitignore // so you can create it and use on your local dev machine // remember last config source added wins if it has the same settings builder.AddJsonFile("appsettings.local.overrides.json", optional: true); // most common use of environment variables would be in azure hosting // since it is added last anything in env vars would trump the same setting in previous config sources // so no risk of messing up settings if deploying a new version to azure builder.AddEnvironmentVariables(); Configuration = builder.Build(); //env.MapPath appBasePath = appEnv.ApplicationBasePath; }
// 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(); app.UseMvc(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.MinimumLevel = LogLevel.Debug; loggerFactory.AddConsole(); ConfigureApplication(app); }
// 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(); app.UseIISPlatformHandler(); app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); app.UseStaticFiles(); app.Use(async (context, next) => { context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Content-Type, x-xsrf-token" }); if (context.Request.Method == "OPTIONS") { context.Response.StatusCode = 200; } else { await next(); } }); app.UseMvc(); SampleData.Initialize(app.ApplicationServices); }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { //Setting up configuration builder var builder = new ConfigurationBuilder() .SetBasePath(appEnv.ApplicationBasePath) .AddEnvironmentVariables(); if (!env.IsProduction()) { builder.AddUserSecrets(); } else { } Configuration = builder.Build(); //Setting up configuration if (!env.IsProduction()) { var confConnectString = Configuration.GetSection("Data:DefaultConnection:ConnectionString"); confConnectString.Value = @"Server=(localdb)\mssqllocaldb;Database=GetHabitsAspNet5;Trusted_Connection=True;"; var identityConnection = Configuration.GetSection("Data:IdentityConnection:ConnectionString"); identityConnection.Value = @"Server=(localdb)\mssqllocaldb;Database=GetHabitsIdentity;Trusted_Connection=True;"; } else { } }
// 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) { app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); loggerFactory.AddConsole(); loggerFactory.AddDebug(); app.UseDeveloperExceptionPage(); app.UseStaticFiles(); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookies", AutomaticAuthenticate = true }); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { AuthenticationScheme = "oidc", SignInScheme = "Cookies", Authority = "https://demo.identityserver.io", PostLogoutRedirectUri = "http://localhost:3308/", ClientId = "hybrid", ClientSecret = "secret", ResponseType = "code id_token", GetClaimsFromUserInfoEndpoint = true, SaveTokens = true }); app.UseMvcWithDefaultRoute(); }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnvironment) { _appEnvironment = appEnvironment; _hostingEnvironment = env; var RollingPath = Path.Combine(appEnvironment.ApplicationBasePath, "logs/myapp-{Date}.txt"); Log.Logger = new LoggerConfiguration() .WriteTo.RollingFile(RollingPath) .CreateLogger(); Log.Information("Ah, there you are!"); // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile("appsettings-filters.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsDevelopment()) { // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets(); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); // Initialize the global configuration static GlobalConfigurationRoot.Configuration = Configuration; }
public Startup( IHostingEnvironment env, IApplicationEnvironment appEnv) { _env = env; // Setup configuration sources. var builder = new ConfigurationBuilder() .SetBasePath(appEnv.ApplicationBasePath) // standard config file .AddJsonFile("config.json") // environment specific config.<environment>.json file .AddJsonFile($"config.{env.EnvironmentName}.json", true /* override if exists */) // standard Windows environment variables .AddEnvironmentVariables(); if (env.IsDevelopment()) { // this one adds not using directive to keep it secret, only a dnx reference // the focus is not on Secrets but on User, so these are User specific settings // we can also make it available only for developers builder.AddUserSecrets(); } Configuration = builder.Build(); }
public Startup(IHostingEnvironment env) { // Set up configuration sources. Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json") .AddEnvironmentVariables() .Build(); }
public Startup(IHostingEnvironment hostingEnvironment, IApplicationEnvironment applicationEnvironment) { Configuration = new ConfigurationBuilder() .SetBasePath(applicationEnvironment.ApplicationBasePath) .AddJsonFile("config.json") .Build(); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } loggerFactory .AddConsole(Configuration.GetSection("Logging")) .AddDebug(); // Use the Default files ['index.html', 'index.htm', 'default.html', 'default.htm'] app.UseDefaultFiles() .UseStaticFiles() .UseIISPlatformHandler() .UseMvc(); // Setup a generic Quotes API EndPoint app.Map("/api/quotes", (config) => { app.Run(async context => { var quotes = "{ \"quotes\":" + " [ { \"quote\": \"Duct tape is like the force. It has a light side, a dark side, and it holds the universe together.\", \"author\":\"Oprah Winfrey\"} ]" + "}"; context.Response.ContentLength = quotes.Length; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(quotes); }); }); }
public static void Initialize(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; }
// 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) { app.UseDipSocket <Chat>("/chat"); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) => app.Run(async(context) => { await context.Response.WriteAsync("Hello World!"); });
// 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(); } else { app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { context.Response.StatusCode = 500; context.Response.ContentType = "text/plain"; var errorFeature = context.Features.Get<IExceptionHandlerFeature>(); if (errorFeature != null) { var logger = loggerFactory.CreateLogger("Global exception logger"); logger.LogError(500, errorFeature.Error, errorFeature.Error.Message); } await context.Response.WriteAsync("There was an error"); }); }); } //Inline middleware to provide a header variable to see the performance of requests. app.Use(async (ncontext, next) => { var watch = new Stopwatch(); //To add Headers AFTER everything you need to do this, listening OnStarting event //in the response such as setting headers, status code, etc. You can't call next.Invoke after the response has been sent to the client. ncontext.Response.OnStarting(state => { watch.Stop(); var httpContext = (HttpContext)state; // Get the elapsed time as a TimeSpan value. TimeSpan ts = watch.Elapsed; // Format and display the TimeSpan value. string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); httpContext.Response.Headers.Add("X-ElapsedTime", new[] { elapsedTime }); return Task.FromResult(0); }, ncontext); watch.Start(); await next.Invoke(); }); app.UseStatusCodePages(); app.UseStaticFiles(); // Add StaticFiles middleware. Return static files (js, css, html) and end pipeline. //In the Configure method, enable middleware to expose the generated Swagger as JSON endpoint(s) //Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(c => { c.RouteTemplate = "api-docs/{documentName}/swagger.json"; c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Host = httpReq.Host.Value); } ); //At this point, you can spin up your application and view the generated Swagger JSON at "/swagger/v1/swagger.json." /*Optionally insert the swagger-ui middleware if you want to expose interactive documentation, specifying the Swagger JSON endpoint(s) to power it from. */ // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint app.UseSwaggerUI(c => { c.SwaggerEndpoint("/api-docs/v1/swagger.json", "RealDox API - V1 Docs"); c.SwaggerEndpoint("/api-docs/v2/swagger.json", "RealDox API - V2 Docs"); //Now you can restart your application and check out the auto-generated, interactive docs at "/swagger". }); // Call UseAuthentication before calling UseMVCWithDefaultRoute or UseMVC. /*Although Identity middleware authenticates requests, authorization (and rejection) occurs only after MVC selects a specific Razor Page or controller and action. */ #region snippet2 app.UseAuthentication(); // Add Identity middleware for authenticate before you access secure resources. #endregion app.UseResponseCompression(); //Compress the response for optimization app.UseMvcWithDefaultRoute(); // Add MVC middleware to the request pipeline. }
public static void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseSwagger("swagger/{apiVersion}/swagger.json"); app.UseSwaggerUi("swagger/ui"); }
public static void AddAuthentication(this IServiceCollection services, IHostingEnvironment hostingEnvironment) { services.AddIdentity<UserIdentity, UserIdentityRole>() .AddEntityFrameworkStores<AdminDbContext>() .AddDefaultTokenProviders(); //For integration tests use only cookie middleware if (hostingEnvironment.IsStaging()) { services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.Cookie.Name = AuthorizationConsts.IdentityAdminCookieName; }); } else { services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = AuthorizationConsts.OidcAuthenticationScheme; options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.Cookie.Name = AuthorizationConsts.IdentityAdminCookieName; }) .AddOpenIdConnect(AuthorizationConsts.OidcAuthenticationScheme, options => { options.Authority = AuthorizationConsts.IdentityServerBaseUrl; options.RequireHttpsMetadata = false; options.ClientId = AuthorizationConsts.OidcClientId; options.Scope.Clear(); options.Scope.Add(AuthorizationConsts.ScopeOpenId); options.Scope.Add(AuthorizationConsts.ScopeProfile); options.Scope.Add(AuthorizationConsts.ScopeEmail); options.Scope.Add(AuthorizationConsts.ScopeRoles); options.SaveTokens = true; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = JwtClaimTypes.Name, RoleClaimType = JwtClaimTypes.Role, }; options.Events = new OpenIdConnectEvents { OnMessageReceived = OnMessageReceived, OnRedirectToIdentityProvider = OnRedirectToIdentityProvider }; }); } }
/// <summary> /// 保存商品图片 /// </summary> /// <param name="goodsType"></param> /// <param name="picType"></param> /// <param name="files"></param> /// <param name="hostingEnvironment"></param> internal void SaveGoodsFiles(int goodsType, int picType, IFormFileCollection files, IHostingEnvironment hostingEnvironment) { long size = 0; foreach (var file in files) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); string saveDir = $@"{ConstantProperty.BaseDir}{ConstantProperty.GoodsImagesDir}"; string dbSaveDir = $@"{ConstantProperty.GoodsImagesDir}"; if (!Directory.Exists(saveDir)) { Directory.CreateDirectory(saveDir); } string exString = filename.Substring(filename.LastIndexOf(".")); string saveName = Guid.NewGuid().ToString("N"); filename = $@"{saveDir}{saveName}{exString}"; size += file.Length; FileModel<string[]> fileCard = new FileModel<string[]>(); using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); string[] fileUrls = new string[] { $@"{dbSaveDir}{saveName}{exString}" }; } var goodsPicCollection = mongo.GetMongoCollection<GoodsPic>(); var goodsPic = goodsPicCollection.Find(x => x.GoodsClass == (GoodsClass)goodsType).FirstOrDefault(); if (goodsPic == null) { goodsPic = new GoodsPic() { GoodsClass = (GoodsClass)goodsType }; goodsPicCollection.InsertOne(goodsPic); } if (goodsPic.HeaderPics == null) { goodsPicCollection.UpdateOne(x => x.GoodsPicID.Equals(goodsPic.GoodsPicID), Builders<GoodsPic>.Update.Set(x => x.HeaderPics, new List<FileModel<string[]>>())); } if (goodsPic.BodyPics == null) { goodsPicCollection.UpdateOne(x => x.GoodsPicID.Equals(goodsPic.GoodsPicID), Builders<GoodsPic>.Update.Set(x => x.BodyPics, new List<FileModel<string[]>>())); } ParamsCreate3Img params3Img = new ParamsCreate3Img() { FileName = filename, FileDir = ConstantProperty.GoodsImagesDir }; params3Img.OnFinish += fileModel => { fileModel.FileID = ObjectId.GenerateNewId(); if (picType == 0) { var update = Builders<GoodsPic>.Update.Push(x => x.HeaderPics, fileModel); goodsPicCollection.UpdateOne(x => x.GoodsPicID.Equals(goodsPic.GoodsPicID), update); } else { var update = Builders<GoodsPic>.Update.Push(x => x.BodyPics, fileModel); goodsPicCollection.UpdateOne(x => x.GoodsPicID.Equals(goodsPic.GoodsPicID), update); } mongo.GetMongoCollection<FileModel<string[]>>("FileModel").InsertOne(fileModel); }; //ThreadPool.QueueUserWorkItem(new WaitCallback(ImageTool.Create3Img), params3Img); new Thread(new ParameterizedThreadStart(ImageTool.Create3Img)).Start(params3Img); } }
public Startup(IConfiguration configuration, IHostingEnvironment env) { Configuration = configuration; Environment = env; }
// 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(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCookieAuthentication(); app.UseCasAuthentication(); app.UseOAuthAuthentication(); // Choose an authentication type app.Map("/login", branch => { branch.Run(async context => { var authType = context.Request.Query["authscheme"]; if (!string.IsNullOrEmpty(authType)) { // By default the client will be redirect back to the URL that issued the challenge (/login?authtype=foo), // send them to the home page instead (/). await context.Authentication.ChallengeAsync(authType, new AuthenticationProperties { RedirectUri = "/" }); return; } context.Response.ContentType = "text/html"; await context.Response.WriteAsync("<html><body>"); await context.Response.WriteAsync("<p>Choose an authentication scheme:</p>"); foreach (var type in context.Authentication.GetAuthenticationSchemes()) { if (string.IsNullOrEmpty(type.DisplayName)) { continue; } await context.Response.WriteAsync($"<a href=\"?authscheme={type.AuthenticationScheme}\">{type.DisplayName}</a><br>"); } await context.Response.WriteAsync("</body></html>"); }); }); // Sign-out to remove the user cookie. app.Map("/logout", branch => { branch.Run(async context => { await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); context.Response.Redirect("/"); }); }); app.Run(async context => { // CookieAuthenticationOptions.AutomaticAuthenticate = true (default) causes User to be set var user = context.User; // This is what [Authorize] calls // var user = await context.Authentication.AuthenticateAsync(AuthenticationManager.AutomaticScheme); // Deny anonymous request beyond this point. if (user == null || !user.Identities.Any(identity => identity.IsAuthenticated)) { // This is what [Authorize] calls // The cookie middleware will intercept this 401 and redirect to /login await context.Authentication.ChallengeAsync(); return; } // Display user information context.Response.ContentType = "text/html"; await context.Response.WriteAsync("<html><body>"); await context.Response.WriteAsync($"<h1>Hello {user.Identity.Name ?? "anonymous"}</h1>"); await context.Response.WriteAsync("<ul>"); foreach (var claim in user.Claims) { await context.Response.WriteAsync($"<li>{claim.Type}: {claim.Value}<br>"); } await context.Response.WriteAsync("</ul>"); await context.Response.WriteAsync("Tokens:<ol>"); await context.Response.WriteAsync($"<li>Access Token: {await context.Authentication.GetTokenAsync("access_token")}</li>"); await context.Response.WriteAsync($"<li>Refresh Token: {await context.Authentication.GetTokenAsync("refresh_token")}</li>"); await context.Response.WriteAsync($"<li>Token Type: {await context.Authentication.GetTokenAsync("token_type")}</li>"); await context.Response.WriteAsync($"<li>Expires At: {await context.Authentication.GetTokenAsync("expires_at")}</li>"); await context.Response.WriteAsync("</ol>"); await context.Response.WriteAsync($"<a href=\"/logout\">Logout</a><br>"); await context.Response.WriteAsync("</body></html>"); }); }
public ReactEnvironmentInitializer(IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory) { _hostingEnvironment = hostingEnvironment; _logger = loggerFactory.CreateLogger <ReactEnvironmentInitializer>(); }
public CabeceraRecuentoController(ICabeceraRecuentoBS cabecera, IConfiguration conf, IHostingEnvironment _env) : base(conf) { _conf = conf; cBS = cabecera; }
public HttpGlobalExceptionFilter(IHostingEnvironment env, ILogger <HttpGlobalExceptionFilter> logger) { this.env = env; this.logger = logger; }
public AgendaWebCoreModule(IHostingEnvironment env) { _env = env; _appConfiguration = env.GetAppConfiguration(); }
public SouvenirsController(WebShopContext context, IHostingEnvironment hEnv) { _context = context; _hostingEnv = hEnv; }
public HomeController(IIdentityServerInteractionService interaction, IHostingEnvironment environment, ILogger<HomeController> logger) { _interaction = interaction; _environment = environment; _logger = logger; }
// 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(); app.UseJsonApi(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplication server, IShamanLogger logger) { base.ConfigureGame(app, env, server, logger); }
public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment) { Configuration = configuration; HostingEnvironment = hostingEnvironment; }
public CustomerinformationModel(IHostingEnvironment env) { _env = env; }
public Startup(IConfiguration config, ILogger <Startup> logger, IHostingEnvironment env) { _config = config; _logger = logger; _env = env; }
public WebResourceManager(IHostingEnvironment environment) { _environment = environment; _scriptUrls = new List <string>(); }
public SampleDataController(ICounterRepository counterRepository, IHostingEnvironment env) { _env = env ?? throw new ArgumentNullException(nameof(env)); _counterRepository = counterRepository ?? throw new ArgumentNullException(nameof(counterRepository)); _storeType = counterRepository.GetType().Name; }
public HomeController(IEmployeeRepository employeeRepository, IHostingEnvironment hostingEnvironment) { this.employeeRepository = employeeRepository; this.hostingEnvironment = hostingEnvironment; }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { }
// 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.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseCors("default"); //app.UseHealthChecks("/liveness", new HealthCheckOptions //{ // Predicate = r => r.Name.Contains("self") //}); //app.UseHealthChecks("/hc", new HealthCheckOptions() //{ // Predicate = _ => true, // ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse //}); // 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<Startup>().LogDebug("Using PATH BASE '{pathBase}'", pathBase); app.UsePathBase(pathBase); } 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(); }
public UserHelper(IHttpContextAccessor contextAccessor, IHostingEnvironment environment) { _contextAccessor = contextAccessor; _environment = environment; }
public static bool CanModifyScheme(this IHostingEnvironment env) { return(env.IsDevelopment() || env.IsEnvironment("INT") || env.IsEnvironment("IntegrationTest")); }
public HomeController(IHostingEnvironment env) { _env = env; }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConfigurationProvider mapper) { mapper.AssertConfigurationIsValid(); app.UseLykkeConfiguration(options => { options.SwaggerOptions = _swaggerOptions; }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IApplicationLifetime lifetime, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Lel Api v1"); }); app.UseMvc(); void OnStart() { var consumer = app.ApplicationServices.GetService <Consumer <Ignore, string> >(); var producer = app.ApplicationServices.GetService <Producer <Null, string> >(); // consumer.Assign(new []{"hello"}.Select(topic => new TopicPartitionOffset(topic, 0, Offset.Beginning)).ToList()); consumer.Subscribe(new [] { "hello", "hello_batch" }); CancellationTokenSource cts = new CancellationTokenSource(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; // prevent the process from terminating. cts.Cancel(); }; var cache = new ConcurrentQueue <string>(); var handlers = new Dictionary <string, Action <string> > { { "hello", message => cache.Enqueue(message) } }; Task.Run(() => { while (true) { var cr = consumer.Consume(cts.Token); if (cr.IsPartitionEOF) { Console.WriteLine("eof"); continue; } Console.WriteLine($"consumed {cr.Value}"); if (handlers.FirstOrDefault(x => x.Key == cr.Topic).Value is Action <string> handler) { Console.WriteLine($"handling {cr.Topic}"); handler(cr.Value); } else { Console.WriteLine($"no handler for {cr.Topic}"); } } }, cts.Token); var timer = new Timer(_ => { var messages = new List <string>(); Console.WriteLine(cache.Count); while (cache.TryDequeue(out var message)) { Console.WriteLine($"batching {message}"); messages.Add(message); } if (messages.Count == 0) { Console.WriteLine("nothing to batch"); return; } producer.ProduceAsync("hello_batch", new Message <Null, string> { Value = string.Join(",", messages) }); }, null, TimeSpan.Zero, TimeSpan.FromSeconds(5)); Console.WriteLine("SUBSCRIBED"); } void OnStop() { var producer = app.ApplicationServices.GetService <Producer <Null, string> >(); var consumer = app.ApplicationServices.GetService <Consumer <Ignore, string> >(); consumer.Close(); producer.Flush(TimeSpan.FromSeconds(2)); } lifetime.ApplicationStarted.Register(OnStart); lifetime.ApplicationStopped.Register(OnStop); }
// 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(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseWebMarkupMin(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); // Add the following to the request pipeline only in development environment. if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // Add Error handling middleware which catches all application specific errors and // send the request to the following path or controller action. app.UseExceptionHandler("/Home/Error"); } // Add the platform handler to the request pipeline. app.UseIISPlatformHandler(); // Add static files to the request pipeline. app.UseStaticFiles(); // Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapRoute("DefaultApi", "api/{controller}/{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.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); var section = Configuration.GetSection("MongoDB"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseIISPlatformHandler(); app.UseCors("AllowAll"); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name:"api", template: "api/{controller}/{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) { SuperDataBase.Configure(env, app.ApplicationServices.GetService<IOptions<AppConfig>>()); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseIISPlatformHandler(); app.UseStaticFiles(); 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.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear()); app.UseStaticFiles(); app.UseIdentity(); // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }