Search code examples
c#asp.net-coresubdomainasp.net-mvc-areasasp.net-core-3.0

Mapping Subdomains to Areas in ASP.Net Core 3


What I want to achieve

  • Mapping my normal domain e.g. example.com to no area if possible.
  • Mapping my subdomain e.g. blog.example.com to a area named blog.

What I have found

There are actually quite a lot of posts regarding to this topic, especially mapping subdomains to areas.

From SO:

Others:

And there are probably even more.

Problem

But there is one big problem, in ASP.Net Core 3 they changed a lot of things, one of them being the routing in general, see mircosoft's devblog. Basically they changed it so everything should now be endpoints.

All the classes e.g. MvcRouteHandler and interfaces e.g. IRouter are basically obsolete now, at least from my understanding. After a while googling around and diggin' in the GitHub repositories I couldn't find anything useful.

Additional information

  • I am using SDK 3.0.100-preview6-012264, but trying to upgrade to SDK 3.0.100-preview7-012821 as soon as possible.
  • I am using a reserve proxy (nginx) which passes the request to the ASP.Net Core Server.

Solution

  • To give an update to this whole situation, with the release of .Net Core 3 you can now make use of the RequireHost method.

    This would look something like the following:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapAreaControllerRoute(
                    name: "Home",
                    areaName: "Home",
                    pattern: "{controller=Home}/{action=Index}")
                 .RequireHost("localhost:5001", "sub.domain.com");
    }
    

    If you remove the Area in the pattern parameter, like in the example, you can achieve exactly that. It is still somewhat hacky, but a lot cleaner. Note, that you would have to put a RequireHost on all of the endpoints in order to get proper default route matching.