Task:
How can you build a case distinction between development state and runtime publish state in the Startup.cs file in Asp.Net Core projects?
Solution:
A) In the initialization, the environment variable is included as a parameter and then queried in ConfigureServices
B) you can use the parameter in the ConfigureServices
A:
Initialize the private variable IHostingEnvironment _env
IHostingEnvironment _env;
public Startup(IHostingEnvironment env) { //--< init >-- var builder = new ConfigurationBuilder(); builder.AddUserSecrets<Startup>(); _env = env;
Configuration = builder.Build(); //--</ init >-- } |
B) Configure parameters
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //-----------< Configure() >----------- if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); }
if (env.EnvironmentName==EnvironmentName.Development) { //------< #Development >-------- //.. //------</ #Development >-------- }
|
Example complete Startup.cs in the project
With the case distinction on Environment = Development
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Freelance.Data; using Freelance.Models; using Freelance.Services; using Microsoft.AspNetCore.Rewrite; using Microsoft.AspNetCore.Http; using Microsoft.IdentityModel.Tokens; //*TokenValidationParameters using System.Text; //*Encoding
namespace Freelance { public class Startup {
public Startup(IHostingEnvironment env) { //--< init >-- var builder = new ConfigurationBuilder(); builder.AddUserSecrets<Startup>();
Configuration = builder.Build(); //--</ init >-- }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //-----------< ConfigureServices() >----------- services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Website_Constants.Connectionstring));
//--< Facebook Api >--
//----< JWT-Token >---- //*reference: www.blinkingcaret.com services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "JwtBearer"; options.DefaultChallengeScheme = "JwtBearer"; })
.AddJwtBearer("JwtBearer", jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = Website_Constants._secretKey,
ValidateIssuer = true, ValidIssuer = "website_freelancer",
ValidateAudience = true, ValidAudience = "webclients_freelancer",
ValidateLifetime = true, //validate the expiration and not before values in the token
ClockSkew = TimeSpan.FromMinutes(5) //5 minute tolerance for the expiration date }; }); //----</ JWT-Token >----
//--< Identity >-- services.AddIdentity<ApplicationUser, IdentityRole>(config => { //< send Register Email > //*prevents registered users from logging in until their email is confirmed. config.SignIn.RequireConfirmedEmail = true; //</ send Register Email > }) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); //--</ Identity >--
services.AddAuthentication().AddFacebook(facebookOptions => { facebookOptions.AppId = Website_Constants.fp_appID; facebookOptions.AppSecret = Website_Constants.fp_secret; }); //--</ Facebook Api >--
// Add application services. services.AddTransient<IEmailSender, EmailSender>();
var optRewrite = new RewriteOptions() .AddRedirectToHttpsPermanent();
services.AddMvc();
//-----------</ ConfigureServices() >----------- }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //-----------< Configure() >----------- if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); }
if (env.EnvironmentName==EnvironmentName.Development) { //------< #Development >-------- //----< redirect http to https >---- try {
app.Use(async (context, next) => { //*check the website-content and all elements like images string sHost = context.Request.Host.HasValue == true ? context.Request.Host.Value : ""; //domain without :80 port .ToString(); sHost = sHost.ToLower(); string sPath = context.Request.Path.HasValue == true ? context.Request.Path.Value : ""; string sQuerystring = context.Request.QueryString.HasValue == true ? context.Request.QueryString.Value : "";
//----< check https >---- // check if the request is *not* using the HTTPS scheme if (!context.Request.IsHttps) { //--< is http >-- string new_https_Url = "https://" + sHost; if (sPath != "") { new_https_Url = new_https_Url + sPath; } if (sQuerystring != "") { new_https_Url = new_https_Url + sQuerystring; } context.Response.Redirect(new_https_Url);
return; //--</ is http >-- } //----</ check https >----
//----< check www >---- if (sHost.IndexOf("www.") == 0) { //--< is www. >-- string new_Url_without_www = "https://" + sHost.Replace("www.", ""); if (sPath != "") { new_Url_without_www = new_Url_without_www + sPath; } if (sQuerystring != "") { new_Url_without_www = new_Url_without_www + sQuerystring; } context.Response.Redirect(new_Url_without_www);
return; //--</ is http >-- } //----</ check www >----
//also check images inside the content await next(); });
} catch (Exception) {
//throw; } //----< redirect http to https >----
//----< redirecturl >---- try {
app.Use(async (context, next) => { string sHost = context.Request.Host.HasValue == true ? context.Request.Host.Value : ""; //domain without :80 port .ToString(); sHost = sHost.ToLower(); string sPath = context.Request.Path.HasValue == true ? context.Request.Path.Value : "";
if (sPath.Length > 1) { string sTest = sPath.Substring(1, 1); if (int.TryParse(sTest, out int i0)) { string sNr_Test = sPath.Substring(1); long PathNr; if (long.TryParse(sNr_Test, out PathNr)) { //--< path isNumeric >-- string new_Url = "https://" + sHost + "/Projects/Details" + sPath; context.Response.Redirect(new_Url);
return; //--</ path isNumeric >-- } } } //----</ check www >---- await next(); });
} catch (Exception) {
//throw; } //----< redirect url >----
//----< DeviceSwitcher Mobile Desktop >---- //*MobileDesktop_Parameter_to_Cookie try { app.Use(async (context, next) => { //----< check Parameter >---- //*Parameter ?v=ViewDevice m=Mobile oder d=Desktop var queryParameter_DeviceSwitcher = context.Request.Query["ds"].FirstOrDefault(); if (queryParameter_DeviceSwitcher != null) { //--< DeviceSwitcher >-- //*has DeviceSwitcher as Parameter //*sendback as cookie CookieOptions options = new CookieOptions(); options.Expires = DateTime.Now.AddDays(100); context.Response.Cookies.Append("ds", queryParameter_DeviceSwitcher, options); //--</ DeviceSwitcher >-- } //----</ check Parameter >----
//also check images inside the content await next(); });
} catch (Exception) {
//throw; } //----</ DeviceSwitcher Mobile Desktop >---- //------</ #Development >-------- }
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes => {
//--< Emoticons >-- routes.MapRoute( name: "🏠", template: "🏠", defaults: new { controller = "Home", action = "Index" } ); routes.MapRoute( name: "📢", template: "📢", defaults: new { controller = "Home", action = "Index" } ); routes.MapRoute( name: "📜", template: "📜", defaults: new { controller = "Projects", action = "Index_all" } ); //--</ Emoticons >--
routes.MapRoute( name: "Projects", // Route name template: "Projects", // URL with parameters defaults: new { controller = "Projects", action = "Index_all" } );
routes.MapRoute( name: "default", template: "{controller=Projects}/{action=Index_all}/{id?}");
} );
//seed dbContext Database.EF_Model.Initialize_DbContext_in_Startup(app.ApplicationServices); //-----------</ Configure() >----------- } } }
|