How to load different Layout pages based on domain name?

Viewed 463

I have a .NET Core project where based on the subdomain I will load different Layout.cshtml pages.

Based on the subdomain a query should be done in the database which will return a code. Based on this code in my ViewStart.cshtml I will load the different layouts.

How can I get the subdomain? And where?

2 Answers

You can simply add your own logic into your views or the global _ViewStart.cshtml that selects the correct layout depending on your own criterias. What I did in the past is add a ViewData property, so my _ViewStart.cshtml looks like this:

@{
  Layout = (string)ViewData["_OverwriteLayout"] ?? "_DefaultLayout";
}

So I just need to set the ViewData["_OverwriteLayout"] value somewhere inside the MVC pipeline. I personally did that within a ResultFilter, so that the logic does not run when non-view results are returned.

That could for example look like this:

public class CustomLayoutResultFilter : IAsyncResultFilter
{
    public Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        if (context.Result is ViewResult viewResult)
        {
            if (context.HttpContext.Request.Host.ToString() == "test.example.com")
                viewResult.ViewData["_OverwriteLayout"] = "_TestLayout";
        }

        return next();
    }
}

You can create multiple Layout and can call them from their ViewStart.cshtml file. Example if you have an second _Layout2.cshtml in a different folder from the other Layout then you create in this folder an _ViewStart.cshtml file with this path

@{
  Layout="~/Views/Shared/[your folder]_Layout2.cshtml"
 }
Related