Asp MVC Routing
By default, Asp MVC is structured in such a way that all URL addresses are structured according to the URL path Domain / Controller / Action / ID.
That means my URL addresses are usually https://Readdy.Net/Notes/Details/99
Custom URL
For external purposes I would like to pass these links however in a short URL thus under Readdy.Net/99. Therefore, you have to implement custom URL redirects.
Under Asp.Net Core 2 MVC, this URL path evaluation is created in the Startup.cs file.
For this one builds in the method Configure (..)
the evaluation logic to the incoming URL path. The startup file is restarted each time a web page is called.
Then read out the current URL from the context.Request and evaluate the domain under context.Request.Host and the first path under context.Request.Path
Task of the code solution here:
Change the path Domain / IDNummer into the path 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 >----
|
Entire 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() >----------- } } }
|