2

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?}");
});
Ryan Durkin
  • 813
  • 6
  • 17

1 Answers1

4

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?}");
});
Ryan
  • 19,118
  • 10
  • 37
  • 53
  • 2
    That's brilliant, thanks! I was attempting to use middleware but I thought GetRouteData() was only a getter and didn't realise you could do .Values.Add() to it. – Ryan Durkin Mar 23 '20 at 10:26
  • Note that sequence matters ! This "app.Use" must come AFTER "app.UseRouting", but before "app.UseEndpoints". Also, new in .NET Core 5: You can also put it into context.Items["host"] = "foobar"; That's not RouteData, though. – Stefan Steiger Sep 02 '21 at 07:46