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.
app.UseEndpoints(endpoints =>
{
// redirect to one route
endpoints.Redirect("/", "/hello");
// redirect permanently to a route
endpoints.RedirectPermanent("/bye", "hello");
// or multiple redirects
endpoints.Redirect(
new ("/hi", "/hello"),
new ("/hola", "/hello"),
new ("/wassup", "/hello", true)
);
endpoints.MapGet("/hello", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
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.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
public static class EndpointExtensions
{
public static IEndpointRouteBuilder Redirect(
this IEndpointRouteBuilder endpoints,
string from, string to)
{
return Redirect(endpoints,
new Redirective(from, to));
}
public static IEndpointRouteBuilder RedirectPermanent(
this IEndpointRouteBuilder endpoints,
string from, string to)
{
return Redirect(endpoints,
new Redirective(from, to, true));
}
public static IEndpointRouteBuilder Redirect(
this IEndpointRouteBuilder endpoints,
params Redirective[] paths
)
{
foreach (var (from, to, permanent) in paths)
{
endpoints.MapGet(from, async http => { http.Response.Redirect(to, permanent); });
}
return endpoints;
}
}
public record Redirective(string From, string To, bool Permanent = false);
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!