Changing RouteData in Asp.Net Core 3.1 in Middleware

Viewed 2141

I've recently updated my .Net Core 2.1 application to 3.1 and there is one part that has not upgraded as expected.

I'd written code to map subdomains to areas as described here

I now realise that the method of using app.UseMvc() should be replaced with app.UseEndpoints() but I can't find anywhere in the 3.1 framework that will allow me to write to the RouteData before app.UseEndpoints()

//update RouteData before this
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        "admin", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    endpoints.MapControllerRoute(
        "default", "{controller=Home}/{action=Index}/{id?}");
});

Is there a way to write to RouteData using Middleware?

I've tried going back to app.UseMvc() as it's still in the framework but MvcRouteHandler doesn't seem to exist anymore

app.UseMvc(routes =>
{
    routes.DefaultHandler = new MvcRouteHandler(); //The type of namespace could not be found
    routes.MapRoute(
        "admin",
        "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(
        "default",
        "{controller=Home}/{action=Index}/{id?}");
});
1 Answers

Try to use custom middleware.

Add a reference to using Microsoft.AspNetCore.Routing and use Httpcontext.GetRouteData() method to achieve RouteData

app.UseRouting();

app.Use(async (context, next) =>
{

    string url = context.Request.Headers["HOST"];
    var splittedUrl = url.Split('.');

    if (splittedUrl != null && (splittedUrl.Length > 0 && splittedUrl[0] == "admin"))
    {
        context.GetRouteData().Values.Add("area", "Admin");
    }

    // Call the next delegate/middleware in the pipeline
    await next();
});

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        "admin", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    endpoints.MapControllerRoute(
        "default", "{controller=Home}/{action=Index}/{id?}");
});
Related