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 Core Umleitung http zu https und www. Zu direkt Domain-Host

19.04.2018 (👁10742)


Dieser Artikel beschreibt, wie man in einem Asp.Net Core MVC Projekt die Adressen von http:// zu https:// umleitet und man zusätzlich den Bereich von www.domain.com zu domain.com ohne www. umleitet.

Dabei werden alle Elemente wie die Webseite und Bilder und Videos welche eingebettet sind umgeleitet auf eine URL->Redirect mit https://Readdy.net  (im Beispiel)

 

In den Asp.Net Core Versionen vor 2.1 muss man hierzu einen Code-Block in die Datei Startup.cs des Asp Projekts einfügen.

Den Code-Block kann man in den Bereich Startup.cs->Configure einfügen.

 

 

Datei in Asp.Net Core

In der Startup.cs Datei des AspNet Core

Core 1 und 2, Version: aspNetCore 2.0

 

Umleitung mit Redirect

Zur Laufzeit werden alle Element in einer Webseite geprüft und nach der Domain, dem Unterpfad in der Domain und eventuellen Querystring Parametern untersucht.

Sobald die URL der Webseite nicht https ist oder ein führendes www. enthält wird der Pfad des Elements auf https:// umgeleitet und mit Response.Redirect(https-url) umgeleitet.

 

 

Startup.cs Code im Block Configure

Umleitung www. und http:

Diesen Block muss man in die startup.cs Datei im Bereich Configure(…) einfügen

            //----< redirect http to https >----

            //* with aspnetcore 2.0

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

            });

            //----< redirect http to https >----

 

 

Effekt Im Browser

Dabei werden alle URL Elemente wie die Datei und die Images der Seite umgeleitet.

 

Beispiele der Umleitung mit http und www.

 

Umleitung von http:// zu https://

 

 

Umleitung von www. zur Domain ohne führendes www.

 

Komplette asp.net core 2 Startup.cs

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 Readdy.Data;

using Readdy.Models;

using Readdy.Services;

using Microsoft.AspNetCore.Rewrite;

namespace Readdy

{

    public class Startup

    {

        public Startup(IConfiguration configuration)

        {

            Configuration = configuration;

        }

        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(Configuration.GetConnectionString("DefaultConnection")));

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

            // Add application services.

            services.AddTransient<IEmailSender, EmailSender>();

            var optRewrite = new RewriteOptions()

            .AddRedirectToHttpsPermanent();

            //--< rewrite http to https >--

            //*with aspnetcore 2.1

            ////*rewrite http: to https: in aspnetcore 2.1

            //services.AddHttpsRedirection(options =>

            //{

            //    options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;

            //    options.HttpsPort = 5001;

            //});

            //--</ rewrite http to https >--

            services.AddMvc();

            //*init sql-server direct

            Database.SQL_Database.cn_String = Configuration.GetConnectionString("DefaultConnection");

            //-----------</ 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");

            }

            //app.UseHttpsRedirection();  //*rewrite http: to https: in aspnetcore 2.1

            //----< redirect http to https >----

            //* with aspnetcore 2.0

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

            });

            //----< redirect http to https >----

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseMvc(routes =>

            {

                //routes.MapRoute(

                //    name: "area",

                //    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                //routes.MapRoute(

                //    name: "demo_05",

                //    template: "{area=demo_05}/{controller=Demo}/{action=demo_start}");

                //routes.MapRoute(

                //    name: "debug_user",

                //    template: "{controller=User}/{action=Edit_Profile}");

                //routes.MapRoute(

                //    name: "debug_edit",

                //    template: "{controller=Notes}/{action=Edit}/{id=11}");

                //--< 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 = "Notes", action = "Index_all" }

                );

                //--</ Emoticons >--

                routes.MapRoute(

                   name: "Notes", // Route name

                   template: "Notes", // URL with parameters

                   defaults: new { controller = "Notes", action = "Index_all" }

               );

                routes.MapRoute(

                    name: "default",

                    template: "{controller=Notes}/{action=Index_all}/{id?}");

            }

            );

            //seed dbContext

            Database.EF_Model.Initialize_DbContext_in_Startup(app.ApplicationServices);

            //-----------</ Configure()  >-----------

        }

    }