[ASP.NET Core MVC Pipeline] Routing Middleware — Custom IRouter

Middleware Pipeline - Routing
Middleware Pipeline
namespace Microsoft.AspNetCore.Routing
{
public interface IRouter
{
VirtualPathData GetVirtualPath(VirtualPathContext context);
Task RouteAsync(RouteContext context);
}
}
public class CustomRouter : IRouter
{
private IRouter _defaultRouter;

public CustomRouter(IRouter defaultRouter)
{
_defaultRouter = defaultRouter;
}

public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
return _defaultRouter.GetVirtualPath(context);
}

public Task RouteAsync(RouteContext context)
{
throw new NotImplementedException();
}
}
public class CustomRouter : IRouter
{
private IRouter _defaultRouter;

public CustomRouter(IRouter defaultRouteHandler)
{
_defaultRouter = defaultRouteHandler;
}

public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
return _defaultRouter.GetVirtualPath(context);
}

public async Task RouteAsync(RouteContext context)
{
var headers = context.HttpContext.Request.Headers;
var path = context.HttpContext.Request.Path.Value.Split('/');

// Look for the User-Agent Header and Check if the Request comes from a Mobile
if (headers.ContainsKey("User-Agent") &&
headers["User-Agent"].ToString().Contains("Mobile"))
{
var action = "Index";
var controller = "";
if (path.Length > 1)
{
controller = path[1];
if (path.Length > 2)
action = path[2];
}

context.RouteData.Values["controller"] = $"Mobile{controller}";
context.RouteData.Values["action"] = action;

await _defaultRouter.RouteAsync(context);
}
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();

app.UseMvc(routes =>
{
routes.Routes.Add(new CustomRouter(routes.DefaultHandler));

routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store