6pak
6pak

Reputation: 41

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.

Upvotes: 4

Views: 4635

Answers (1)

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30545

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}");
        });
    } 

Upvotes: 2

Related Questions