本文整理汇总了C#中IHostingEnvironment.IsProduction方法的典型用法代码示例。如果您正苦于以下问题:C# IHostingEnvironment.IsProduction方法的具体用法?C# IHostingEnvironment.IsProduction怎么用?C# IHostingEnvironment.IsProduction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IHostingEnvironment
的用法示例。
在下文中一共展示了IHostingEnvironment.IsProduction方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Startup
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
{
}
}
示例2: Startup
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("version.json")
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// 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 will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
else if (env.IsStaging() || env.IsProduction())
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: false);
}
Configuration = builder.Build();
Configuration["version"] = new ApplicationEnvironment().ApplicationVersion; // version in project.json
}
示例3: ConfigureConfiguration
/// <summary>
/// Creates and configures the application configuration, where key value pair settings are stored. See
/// http://docs.asp.net/en/latest/fundamentals/configuration.html
/// http://weblog.west-wind.com/posts/2015/Jun/03/Strongly-typed-AppSettings-Configuration-in-ASPNET-5
/// </summary>
/// <param name="applicationEnvironment">The location the application is running in</param>
/// <param name="hostingEnvironment">The environment the application is running under. This can be Development,
/// Staging or Production by default.</param>
/// <returns>A collection of key value pair settings.</returns>
private static IConfiguration ConfigureConfiguration(
IApplicationEnvironment applicationEnvironment,
IHostingEnvironment hostingEnvironment)
{
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
.SetBasePath(applicationEnvironment.ApplicationBasePath);
// Add configuration from the config.json file.
configurationBuilder.AddJsonFile("config.json");
// Add configuration from an optional config.development.json, config.staging.json or
// config.production.json file, depending on the environment. These settings override the ones in the
// config.json file.
configurationBuilder.AddJsonFile($"config.{hostingEnvironment.EnvironmentName}.json", optional: true);
// This reads the configuration keys from the secret store. This allows you to store connection strings
// and other sensitive settings, so you don't have to check them into your source control provider. See
// http://go.microsoft.com/fwlink/?LinkID=532709 and
// http://docs.asp.net/en/latest/security/app-secrets.html
configurationBuilder.AddUserSecrets();
// Add configuration specific to the Development, Staging or Production environments. This config can
// be stored on the machine being deployed to or if you are using Azure, in the cloud. These settings
// override the ones in all of the above config files.
// Note: To set environment variables for debugging navigate to:
// Project Properties -> Debug Tab -> Environment Variables
// Note: To get environment variables for the machine use the following command in PowerShell:
// $env:[VARIABLE_NAME]
// Note: To set environment variables for the machine use the following command in PowerShell:
// $env:[VARIABLE_NAME]="[VARIABLE_VALUE]"
// Note: Environment variables use a colon separator e.g. You can override the site title by creating a
// variable named AppSettings:SiteTitle. See
// http://docs.asp.net/en/latest/security/app-secrets.html
configurationBuilder.AddEnvironmentVariables();
// $Start-ApplicationInsights$
// Push telemetry data through the Azure Application Insights pipeline faster in the development and
// staging environments, allowing you to view results immediately.
configurationBuilder.AddApplicationInsightsSettings(developerMode: !hostingEnvironment.IsProduction());
// $End-ApplicationInsights$
return configurationBuilder.Build();
}
示例4: Startup
public Startup(IApplicationEnvironment appEnv, IHostingEnvironment env)
{
var logFile = Path.Combine(appEnv.ApplicationBasePath, "logfile.txt");
Log.Logger = new LoggerConfiguration()
.WriteTo.TextWriter(File.CreateText(logFile))
.CreateLogger();
Configuration = new ConfigurationBuilder()
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json")
.AddEnvironmentVariables()
.Build();
if (env.IsDevelopment())
{
Debug.WriteLine("IsDev");
}
if (env.IsProduction())
{
Debug.WriteLine("IsProd");
}
}
示例5: Configure
// 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, IOptions<TokenProviderOptions> tokenOptions, AppDbContext dbContext)
{
if (env.IsProduction())
{
dbContext.Database.Migrate();
}
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404 &&
!Path.HasExtension(context.Request.Path.Value) &&
!context.Request.Path.Value.StartsWith("/api/"))
{
context.Request.Path = "/index.html";
await next();
}
});
var jwtOptions = tokenOptions.Value;
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = jwtOptions.TokenValidationParameters
});
app.UseMiddleware<TokenProviderMiddleware>();
app.UseMvc();
app.UseStaticFiles();
}
示例6: Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
GetHabitsContext context, GetHabitsIdentity identContext, GoogleAuthHelper googleAuthHelper, ApplicationHelper appHelper)
{
if (env.IsProduction())
{
loggerFactory.AddConsole(LogLevel.Verbose);
}
else
{
loggerFactory.AddConsole(LogLevel.Verbose);
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage(opt => opt.EnableAll());
}
app.UseStaticFiles();
//TODO do checks
context.Database.Migrate();
identContext.Database.Migrate();
app.UseCookieAuthentication(options =>
{
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.LoginPath = new PathString("/account/login");
options.LogoutPath = new PathString("/account/logoff");
options.AuthenticationScheme = appHelper.DefaultAuthScheme;
});
app.UseCookieAuthentication(options =>
{
options.AutomaticAuthenticate = false;
options.AuthenticationScheme = appHelper.TempAuthScheme;
});
var clientId = Configuration.GetSection("Authentication:Google:ClientId").Value;
var clientSecret = Configuration.GetSection("Authentication:Google:ClientSecret").Value;
app.UseGoogleAuthentication(options =>
{
options.ClientId = clientId;
options.ClientSecret = clientSecret;
options.AuthenticationScheme = googleAuthHelper.ProviderName;
options.AutomaticAuthenticate = false;
options.SignInScheme = appHelper.TempAuthScheme;
options.Events = new OAuthEvents()
{
OnRemoteError = async errorContext =>
{
var error = errorContext.Error;
errorContext.Response.Redirect("/error?ErrorMessage=" + UrlEncoder.Default.UrlEncode(errorContext.Error.Message));
errorContext.HandleResponse();
await Task.FromResult(0);
}
};
});
var localizationOptions = new RequestLocalizationOptions()
{
SupportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("ru-RU")
},
SupportedUICultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("ru-RU")
}
};
localizationOptions.RequestCultureProviders.Insert(0, new FirstAddressSegmentCultureProvider(appHelper));
app.UseRequestLocalization(localizationOptions, new RequestCulture("ru-RU"));
app.UseIISPlatformHandler();
app.UseMvc(routeBuilder =>
{
routeBuilder.MapRoute("applicationRoute", "app/{*all}", new { controller = "App", action = "Index"});
routeBuilder.MapRoute("localizedRoute", "{langname}/{controller=Home}/{action=Index}/{id?}", null, new { langname = new RequestLocalizedRouteConstraint(appHelper.LangNameAndCultureNameCorresponding.Keys) });
routeBuilder.MapRoute("unLocalizedRoute", "{*allPath}", new { controller = "Localize", action = "UnLocalizedRequest" }, new { allPath = new RequestUnLocalizedRouteConstraint(appHelper.LangNameAndCultureNameCorresponding.Keys) });
});
}
示例7: InitApnsBroker
private void InitApnsBroker(GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment)
{
if(string.IsNullOrWhiteSpace(globalSettings.Push.ApnsCertificatePassword)
|| string.IsNullOrWhiteSpace(globalSettings.Push.ApnsCertificateThumbprint))
{
return;
}
var apnsCertificate = GetCertificate(globalSettings.Push.ApnsCertificateThumbprint);
if(apnsCertificate == null)
{
return;
}
var apnsConfig = new ApnsConfiguration(hostingEnvironment.IsProduction() ?
ApnsConfiguration.ApnsServerEnvironment.Production : ApnsConfiguration.ApnsServerEnvironment.Sandbox,
apnsCertificate.RawData, globalSettings.Push.ApnsCertificatePassword);
_apnsBroker = new ApnsServiceBroker(apnsConfig);
_apnsBroker.OnNotificationFailed += ApnsBroker_OnNotificationFailed;
_apnsBroker.OnNotificationSucceeded += (notification) =>
{
Debug.WriteLine("Apple Notification Sent!");
};
_apnsBroker.Start();
var feedbackService = new FeedbackService(apnsConfig);
feedbackService.FeedbackReceived += FeedbackService_FeedbackReceived;
feedbackService.Check();
}
示例8: Configure
//.........这里部分代码省略.........
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
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");
}
// Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline.
app.UseApplicationInsightsExceptionTelemetry();
// Add static files to the request pipeline.
app.UseStaticFiles();
// Add cookie-based authentication to the request pipeline.
app.UseIdentity();
// Add token-based protection to the request inject pipeline
app.UseTokenProtection(new TokenProtectedResourceOptions
{
Path = "/api/request",
PolicyName = "api-request-injest"
});
// Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
// For more information see http://go.microsoft.com/fwlink/?LinkID=532715
if (Configuration["Authentication:Facebook:AppId"] != null)
{
var options = new FacebookOptions
{
AppId = Configuration["Authentication:Facebook:AppId"],
AppSecret = Configuration["Authentication:Facebook:AppSecret"],
BackchannelHttpHandler = new FacebookBackChannelHandler(),
UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name"
};
options.Scope.Add("email");
app.UseFacebookAuthentication(options);
}
if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null)
{
var options = new MicrosoftAccountOptions
{
ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"],
ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"]
};
app.UseMicrosoftAccountAuthentication(options);
}
//TODO: mgmccarthy: working on getting email from Twitter
//http://www.bigbrainintelligence.com/Post/get-users-email-address-from-twitter-oauth-ap
if (Configuration["Authentication:Twitter:ConsumerKey"] != null)
{
var options = new TwitterOptions
{
ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"],
ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"]
};
app.UseTwitterAuthentication(options);
}
if (Configuration["Authentication:Google:ClientId"] != null)
{
var options = new GoogleOptions
{
ClientId = Configuration["Authentication:Google:ClientId"],
ClientSecret = Configuration["Authentication:Google:ClientSecret"]
};
app.UseGoogleAuthentication(options);
}
// Add MVC to the request pipeline.
app.UseMvc(routes =>
{
routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller}/{action=Index}/{id?}");
routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
});
// Add sample data and test admin accounts if specified in Config.Json.
// for production applications, this should either be set to false or deleted.
if (!env.IsProduction())
{
context.Database.Migrate();
}
if (Configuration["SampleData:InsertSampleData"] == "true")
{
sampleData.InsertTestData();
}
if (Configuration["SampleData:InsertTestUsers"] == "true")
{
await sampleData.CreateAdminUser();
}
}
示例9: SetupDatabase
private static void SetupDatabase(IApplicationBuilder app, IHostingEnvironment env)
{
// For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
var identityDbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
var dataDbContext = serviceScope.ServiceProvider.GetService<ExocortexDbContext>();
if (env.IsDevelopment())
{
identityDbContext.Database.EnsureCreated();
dataDbContext.Database.Migrate();
}
else if (env.IsProduction())
{
identityDbContext.Database.EnsureCreated();
dataDbContext.Database.Migrate();
}
}
}
示例10: Configure
// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.MinimumLevel = LogLevel.Debug;
loggerFactory.AddConsole();
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
// set locale to GB
app.UseRequestLocalization(new RequestCulture(new CultureInfo("en-GB")));
// Add the following to the request pipeline only in development environment.
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
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 static files to the request pipeline.
app.UseStaticFiles();
app.UseCookieAuthentication(options =>
{
options.AutomaticAuthenticate = true;
options.LoginPath = "/";
if (env.IsProduction())
{
options.CookieSecure = CookieSecureOption.Always;
}
});
// Add MVC to the request pipeline.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}");
});
// allow pinging and ponging... :)
app.Use((context, next) =>
{
Console.WriteLine("{0} {1}{2}{3}",
context.Request.Method,
context.Request.PathBase,
context.Request.Path,
context.Request.QueryString);
if (context.Request.Path.StartsWithSegments("/ping"))
{
return context.Response.WriteAsync("pong");
}
return next();
});
}