As web applications evolve, and we better understand the problems we are solving, reorganizing routes becomes an annoying inevitability. In this short but helpful post, we’ll add a few extension methods to the IEndpointRouteBuilder
interface that makes mapping redirects a breeze.
Using Redirect and RedirectPermanent
Before we see the implementation of our Redirect
extension methods, let’s see how we’ll use them in our endpoint registration code. We’ll be using C# 9 features like target type new and records to keep code noise to a minimum.
With a few straightforward calls to Redirect
, RedirectPermanent
, and Redirect(params Redirective[])
, we get a powerful route redirecting API. Isn’t that great?! Of course, it is. Let’s see how we can implement it in our ASP.NET Core web applications.
Implementing Redirect and RedirectPermanent Extension methods
The implementation of our extension methods requires using the MapGet
method on our IApplicationBuilder
instance, and then we need to call the Redirect
method on our HttpContext
. In general, these extension methods operate similarly.
There you have it! A set of simple extension methods sure to make the annoying task of remapping and redirecting routes easier for you and your web development team. Enjoy!