问题
One way of configuring startup.cs is to check the environment based on an environmental variable, and run the appropriate code within the Configure method:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// 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.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
For the app I'm working on, I can't guarantee that I will have access to clients' machines to add the ASPNETCORE_ENVIRONMENT environmental variable to make sure they're routed to the correct exception page. But I also don't want to keep having to remember to comment out certain code when I'm about to publish the project.
How can I instead get the project's configuration name to determine what code I want run?:
Here's some pseudocode of what I'd like to accomplish:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//I get the configuration name (could be "Debug", "Development", or "Release)
//from the list in the photo
string configurationName = GetConfigurationName();
//I compare the name to determine what error page to show
if (configurationName == "Debug" || configurationName == "Development")
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// 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.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
回答1:
If you can't make it work with the environment, you could use a preprocessor directive. When deploying your code to production, make sure you are compiling with RELEASE as solution configuration:
#if DEBUG
app.UseDeveloperExceptionPage();
#elif RELEASE
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
#endif
You can find some nice examples here:
来源:https://stackoverflow.com/questions/62174785/how-to-configure-startup-cs-based-on-solution-configuration-and-not-environment