Readdy Write  
0,00 €
Your View Money
Views: Count
Self 20% 0
Your Content 60% 0

Users by Links 0
u1*(Content+Views) 10% 0
Follow-Follower 0
s2*(Income) 5% 0

Count
Followers 0
Login Register as User

Asp.Net Core Startup.cs mit Environment Development erweitern

17.08.2018 (๐Ÿ‘514)


 

 

Aufgabe:

Wie kann man in der Startup.cs Datei in Asp.Net Core Projekten eine Fallunterscheidung auf Entwicklungszustand und Runtime-Publish Zustand einbauen.

Lรถsung:

A) Man bindet in der Initialisierung die Environment Variable als Parameter ein und frรคgt diese dann in ConfigureServices ab

B) man kann in der ConfigureServices den Parameter mit verwenden

A:

Die private Variable IHostingEnvironment _env initialisieren

IHostingEnvironment _env;

 

public Startup(IHostingEnvironment env)

{

    //--< init >--

    var builder = new ConfigurationBuilder();

    builder.AddUserSecrets<Startup>();

    _env = env;

 

    Configuration = builder.Build();

    //--</ init >--

}

B) Configure-Parameter

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 >--------

    }

Beispiel komplette Startup.cs im Projekt

Mit der Fallunterscheidung auf 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<ApplicationUserIdentityRole>(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<IEmailSenderEmailSender>();

 

            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()  >-----------

        }

    }

}