Free Code Snippets in C#, Net Framework, Office 365, ASP.Net,WPF, Visual Studio, SQL Server, Antivirus free
#

Asp core redirect http to https and www. To directly domain host

 

This article describes how to redirect the addresses from http: // to https: // in an Asp.Net Core MVC project and additionally to move the domain from www.domain.com to domain.com without www. redirects.

All elements such as the website and pictures and videos embedded are redirected to a URL-> Redirect with https://Readdy.net (in the example)

 

In the Asp.Net Core versions prior to 2.1 you have to insert a code block into the file Startup.cs of the Asp project.

The code block can be inserted in the area Startup.cs-> Configure.

 

 

File in Asp.Net Core

In the Startup.cs file of the AspNet Core

Core 1 and 2, version: aspNetCore 2.0

 

Redirect with Redirect

At runtime, all elements in a web page are checked and examined for the domain, the subpath in the domain and any querystring parameters.

Once the URL of the website is not https or a leading www. contains the path of the element is redirected to https: // and redirected with Response.Redirect (https-url).

 

 

Startup.cs code in the block Configure

Redirection www. and http:

You have to insert this block into the startup.cs file in the area Configure (...)

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

 

 

Effect in the browser

All URL elements such as the file and the images of the page are redirected.

 

Examples of redirection with http and www.

 

Redirect from http: // to https: //

 

 

Redirection from www. to the domain without leading www.

 

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

        }

    }

}

 

Mobile
»
Asp core redirect http to https and www. To directly domain host
»
Asp MVC Core: URL Query Parameters
»
Asp Core MVC: New Define Startup File, Start Controller View
»
Asp MVC: HTML links instead of server side links
»
AmbiguousActionException: Multiple actions matched
»
Asp.Net Core MVC: Create Alternative URL Routes

.

Contact for Jobs, Project Requests: raimund.popp@microsoft-programmierer.de