The concept of Routing is very vast and I have covered it in 6 tutorials which are:
So make sure you cover each of these one by one.
ASP.NET Core 3.0 brings a new concept of Endpoint routing which scans incoming HTTP requests and maps them to Endpoint in the application. Endpoints can be controllers, razor pages, Blazor, SignalR and gRPC. This allows different types of Dot Net apps to work together without any problem. Endpoint Routing improves the overall routing mechanism feature in Dot Net.
To understand Endpoint Routing we create a small example. In the below code we are trying to find out the Controller’s name, in the Configure method of the Startup.cs file when not using Endpoint Routing.
app.Use(async (context, next) =>
{
var controller = context.Request.RouteValues["controller"];
await next();
});
In this scenario I get null value for the controller variable, and this is shown by the breakpoint value as illustrated in the below image:
If you did not understand where to put this code, I am giving you the full code of my Configure method below:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStaticFiles();
app.Use(async (context, next) =>
{
var controller = context.Request.RouteValues["controller"];
await next();
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Now we make use of Enpoint Routing in the Configure method of Startup class as shown below:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStaticFiles();
app.UseRouting();
app.Use(async (context, next) =>
{
var controller = context.Request.RouteValues["controller"];
await next();
});
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Run the application and check the value of ‘controller’ through the breakpoint. This time we will get the value of the controller in the variable. Now we are getting a lot of information on the routes which enables us to make complex routing codes with ease.
Check the below image that shows the breakpoint’s value:
By default the ASP.NET 3.0 and later versions have Endpoint routing enabled. You only have to add app.UseRouting() in the Configure() method of the Startup.cs file, before any other middleware that needs to access routing:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
//Define endpoint routes here
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Endpoint routing’s two extension methods are:
Endpoint routing supports many route configuration methods, some important ones are:
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); });
This sets the endpoint routing for Razor Pages. Sample endpoint configuration as below:
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
Adds a route that only matches HTTP GET requests. The code given below will show the ‘Hello world’ message for the root page of the website in the browser:
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", context => context.Response.WriteAsync("Hello world"));
});
Similarly, we can configure other Http verb route like MapPost, MapDelete, MapPut, etc.
Endpoint routing makes the ASP.NET Core framework more flexible since it decouples the route matching and resolution functionality from the endpoint dispatching functionality, which until now was all bundled in with the MVC middleware.
Let’s take a few examples to understand them:
Suppose you have to enable CORS only on a single endpoint. You can do this simply as:
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/someurl", context => context.Response.WriteAsync("Hello world")).RequireCors("policy-name");
});
You can also enable Authorization on a single endpoint so that only ‘Admin’ roles are able to view the corresponding URL like this:
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/secured",
context => context.Response.WriteAsync("Secured Page"))
.RequireAuthorization(new AuthorizeAttribute() { Roles = "admin" });
});
You already know that when there are more than one routes defined in an application, then the routes are applied in the order in which they are defined. You can now override this thing as you have prior information about a lot of route things.
Check the below code where I am redirecting users to /contact page when Controller called is ‘Business’ and action method is ‘Deal’.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
// Redirect code
app.Use(async (context, next) =>
{
var controller = context.Request.RouteValues["controller"];
var action = context.Request.RouteValues["action"];
if ((controller.ToString() == "Business") && (action.ToString() == "Deal"))
{
context.Response.Redirect("/contact");
}
await next();
});
app.UseEndpoints(endpoints =>
{
//Define endpoint routes here
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
You can download the full source code of this tutorial:
If you have worked with Dependency Injection (DI) feature of ASP.NET Core then you had come across a situation where you need to add context information to a service. Then this service is made available to the controller using DI. Here you can make use of Endpoint routing quite easily and bypass the complexities of Dependency Injection.
This situation is explained by Rick Strah in his blog very well.
Updating your older routes to Endpoint routing is easy. Go to the Startup.cs file where your old routes are written. You only have to add all the routes inside the app.UseMvc() method to inside the endpoints.MapControllerRoute() method. See –
app.UseEndpoints(endpoints =>
{
// add the old routes
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
However if you want to keep working with your old routes then you can disable the Endpoint routing from the ConfigureServices() method:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(option => option.EnableEndpointRouting = false); // disable endpoint routing
}
Endpoint routing allows ASP.NET Core applications to determine the endpoint that will be dispatched, early on in the middleware pipeline, and so makes the framework more flexible.
I hope you liked this tutorial, so please share this on your facebook and twitter accounts, and let the knowledge flows
Great article! Not just this, but all articles here are fabulous.
My question is with endpoint routing, if I provide defaults like:
endpoints.MapControllerRoute(
name: “default”,
pattern: “{controller=Admin}/{action=Index}/{id?}”);
Why does my browser not show locahost:2131/admin/index, it only shows localhost:2131
i searched the internet but haven’t found an answer just as yet. Pls revert!
Hello,
Your code is looks correct, may be some issue with browser caching. Try incognito mode of the browser and see if it works.
Thank you.