Search code examples
c#asp.net-mvcrazor

Is there any way to get around the RenderBody() requirement?


I have an ASP.NET MVC web application, all the pages in which use a single master Layout.cshtml page. Although I usually want to RenderBody(), I have a site shutdown mechanism that can be enabled in my database so I basically want to have a layout page that looks something like:

@if(DbHelper.SiteIsShutDown) {
    <h1>Site is shut down temporarily</h1>
}
else {
    <h1>Welcome to the site</h1>
    @RenderBody()
}

The trouble is that if SiteIsShutDown is true, then RenderBody() doesn't get called and I get the exception:

The "RenderBody" method has not been called for layout page...

So is there a way I can get round this? I just want to render some output from my layout page, and nothing from my view page.


Solution

  • In the end I decided to go with something pretty similar to Jerad Rose's solution, but modified so it just serves up a static file at the root called SiteDisabled.htm, and also modified so that it doesn't go into an infinite redirect loop when the site is disabled:

    protected void Application_BeginRequest(object sender, EventArgs ea) {
        string siteDisabledFilePath = "/SiteDisabled.htm";
    
        if (CachingAndUtils.IsSiteDisabled && HttpContext.Current.Request.FilePath != siteDisabledFilePath) {
            HttpContext.Current.Response.Redirect(siteDisabledFilePath);
        }
    }