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

Benutzerdefinierte URL Weiterleitung bei Asp Net Core MVC

20.05.2018 (👁16294)


 

Asp MVC Routing

Asp MVC ist standardmässig so aufgebaut, dass alle URL Adressen nach dem URL Pfad Domain/Controller/Action/ID aufgebaut sind.

Das heißt meine URL Adressen sind normalerweise https://Readdy.Net/Notes/Details/99

 

Benutzerdefinierte URL

Für externe Zwecke möchte ich diese Links aber in einer Kurz-URL weitergeben also unter Readdy.Net/99  . Deshalb muss man hierzu benutzerdefiniert URL Weiterleitungen einbauen.

Unter Asp.Net Core 2 MVC bildet man diese URL Pfad-Auswertung in der Startup.cs Datei.

Hierzu baut man in der Methode

Configure(..)

die Auswerte-Logik zum ankommenden URL Pfad ein. Die Startup-Datei wird bei jedem Aufruf einer Webseite erneut gestartet.

Dann liest man die aktuel URL aus dem context.Request aus und wertet die Domain unter

context.Request.Host

aus und den ersten Pfad unter

context.Request.Path

 

Aufgabe der Code Lösung hier:

Wandle den Pfad Domain/IDNummer um in den Pfad  Domain/Controller/Action/ID

 

 

Asp.net Core 2 MVC

 

Startup.cs

           //----< 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 + "/Notes/Details" + sPath;

                                context.Response.Redirect(new_Url);

                                return;

                                //--</ path isNumeric >--

                            }

                        }

                    }

                    //----</ check www >----

                    await next();

                });

            }

            catch (Exception)

            {

                //throw;

            }

            //----< redirect url >----

 

 

 

 

 

 

 

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

using Microsoft.AspNetCore.Http;

namespace Readdy

{

    public class Startup

    {

        public Startup(IHostingEnvironment env)

        {

            var builder = new ConfigurationBuilder();

            builder.AddUserSecrets<Startup>();

            Configuration = builder.Build();

        }

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

            //Website_Constants.Connectionstring = Configuration["DefaultConnection"].ToString();

            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Website_Constants.Connectionstring));

            //--< Facebook Api >--

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

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

            }

            //----< 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 + "/Notes/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 >----

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

        }

    }

}