Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subdomain routing in ASP.NET Core 3.0 RazorPages

I'm using ASP.NET Core 3.0 with razor pages, and I want to route sub1.test.local to Pages/Sub1 and sub2.test.local to Pages/Sub2. I tried create custom page convention, but this is completely different from MVC routes, so I'm asking here.

like image 507
6pak Avatar asked Oct 16 '25 13:10

6pak


1 Answers

Michael Graf has post about this.

You first need to create custom Router by overriding MvcRouteHandler, then you need to use this Router class inside your Mvc Routes configuration.

public class AreaRouter : MvcRouteHandler, IRouter
{
    public new async Task RouteAsync(RouteContext context)
    {
        string url = context.HttpContext.Request.Headers["HOST"];

        string firstDomain = url.Split('.')[0];
        string subDomain = char.ToUpper(firstDomain[0]) + firstDomain.Substring(1);

        string area = subDomain;

        context.RouteData.Values.Add("area", subDomain);

        await base.RouteAsync(context);
    }
}

In Startup config,

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseMvc(routes =>
        {
            routes.DefaultHandler = new AreaRouter();
            routes.MapRoute(name: "areaRoute",
                template: "{controller=Home}/{action=Index}");
        });
    } 
like image 159
Derviş Kayımbaşıoğlu Avatar answered Oct 19 '25 03:10

Derviş Kayımbaşıoğlu