0

How to Redirect to view from global.asax?

Below is my code. It gives me HTTP Error 500.19 - Internal Server Error.

public void Application_BeginRequest(object sender, EventArgs e)
    {
        if (ConfigurationManager.AppSettings["MaintenanceMode"] == "true")
        {
            //  if (!Request.IsLocal)
            //  {
            Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetNoStore();
            Server.ClearError();
            Response.Clear();

            HttpContext.Current.Response.Redirect("~/Views/Account/MaintenancePage.cshtml");
            // }
        }
    }
Hob
  • 139
  • 1
  • 13

2 Answers2

2

Add MaintenancePage GET action in your Account controller, which looks like this:

[AllowAnonymous]
[HttpGet]
public IActionResult MaintenancePage()
{
    return View();
}

And then point to this action this way to prevent infinite redirection loop:

HttpContext.Current.RewritePath("/Account/MaintenancePage");

Hope that helps.

Dmitry Pavlov
  • 30,789
  • 8
  • 97
  • 121
1

In cases of maintenance mode, or error checking, I redirect to a static html page using Server.Transfer.

Server.Transfer("/Error.html");

I keep Error.html in the root of the project.

tblakely
  • 21
  • 2
  • Its a MVC application. So Instead of keeping in root directory I created a view inside views/account folder – Hob Sep 19 '18 at 19:56
  • By the way, static page is just a file so for maintenace purposes it makes sense to consider this scenario instead of controller actions. https://stackoverflow.com/questions/17949460/how-do-you-request-static-html-files-under-the-views-folder-in-asp-net-mvc – Dmitry Pavlov Sep 19 '18 at 20:34
  • Already have one view folder. I do not want to duplicate the views. – Hob Sep 20 '18 at 13:19