If you want to look at the previous articles of this series, please visit the links given below.
Routing is integrated with the pipeline as an IHttpModule and when a route was resolved, it would bypass the rest of the pipeline and delegate to the final IHttpHandler through a new factory-type interface, the IRouteHandler.
It was through this IRouteHandler that MVC integrated with Routing, and this is important, because generally MVC-style URL's are extensionless, so the routing system enabled these types of URLs to be mapped to a specific IHttpHandler and in the case of MVC, this means mapping to the MVCHandler, which is the entry point for Controller/action execution. This means we didn't need to express a whole host of <httpHandler> rules for each unique route in our web.config file.
The MVC integration provided the MapRoute methods as extensions for a RouteCollection. Each route instance provides a Handler property - which by default is set to the MVCRouteHandler (through the IRouteHandler abstraction),
- routes.MapRoute(
- "Default",
- "{controller}/{action}/{id}",
- new { controller = "Home", action = "Index", Id = UrlParameter.Optional });
This method call creates a Route instance with the MVCRouteHandler set. You can always override it, as shown.
- var route = routes.MapRoute("Default", "{controller}/{action}/{id}", new {
- controller = "Home", action = "Index", Id = UrlParameter.Optional
- });
- route.Handler = new MyCustomHandler();
In current Routing (System.Web.Routing), routes are registered into a RouteCollection, which forms a linear collection of all the possible routes. When the routes are being processed against an incoming URL, they form a top-down queue, where the first Route that matches it wins. For ASP.NET 4.x, there can only be one route collection for your Application, so all of your routing requirements have to be fulfilled by this instance.
The new Routing framework is based around the concept of an IRouter,
- public interface IRouter {
- Task RouteAsync(RouteContext context);
- VirtualPathData GetVirtualPath(VirtualPathContext context);
- }
An instance of RouterMiddleware can be created, using any instance of IRouter. You can think of this as the root of a routing tree. Routers can be implemented any way and can be plugged directly into the pipeline, using middleware. To handle the classical routing collection (or route table), we now have an IRouteCollection abstraction, itself extending IRouter. This means that any RouteCollection instance acts as a router and can be used directly with the middleware.
Using Routing Middleware
To implement route in the .NET Core Application, first add NuGet package Microsoft.AspNetCore.Routing.
Add routing to the Service container in Startup.cs.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddRouting();
- }
Routes must be configured in the Configure method in the Startup class. The sample given below uses API.
- RouteBuilder
- Build
- MapGet Matches only HTTP GET requests
- UseRouter
If you are configuring a single route, call app.UseRouter, which is passed in an IRouter instance. You won't need to call RouteBuilder. The framework provides a set of extension methods to creating routes such as
- MapRoute
- MapGet
- MapPost
- MapPut
- MapDelete
- MapVerb
Some of these methods such as MapGet require a RequestDelegate to be provided. The RequestDelegate will be used as the route handler when the route matches. Other methods in this family allow configuring a middleware pipeline, which will be used as the route handler. If the Map method doesn't accept a handler, such as MapRoute, then it will use the DefaultHandler. The Map[Verb] methods use the constraints to limit the route to the HTTP Verb in the method name.
Now, write down the code given below.
Program.cs
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Hosting;
- namespace Prog5_SimpleRoute {
- public class Program {
- public static void Main(string[] args) {
- var host = new WebHostBuilder().UseKestrel().UseContentRoot(Directory.GetCurrentDirectory()).UseIISIntegration().UseStartup < Startup > ().UseApplicationInsights().Build();
- host.Run();
- }
- }
- }
Startup.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- using Microsoft.AspNetCore.Routing;
- namespace Prog5_SimpleRoute {
- public class Startup {
-
-
- public void ConfigureServices(IServiceCollection services) {
- services.AddRouting();
- }
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
- loggerFactory.AddConsole();
- if (env.IsDevelopment()) {
- app.UseDeveloperExceptionPage();
- }
- var route = new RouteBuilder(app);
- route.MapGet("", context => context.Response.WriteAsync("This is Default Route"));
- route.MapGet("part1", context => context.Response.WriteAsync("This is Sub child Route"));
- route.MapGet("cricket", context => context.Response.WriteAsync("This is Route Details for Cricket"));
- route.MapGet("detail/{rank}", context => context.Response.WriteAsync($ "Route Rank is : {context.GetRouteValue("
- rank ")}"));
- app.UseRouter(route.Build());
- app.Run(async(context) => {
- await context.Response.WriteAsync("Hello World!");
- });
- }
- }
- }
Now, run the project and the the different output is given below, as per the route value.
You can read the next part here,