Antoine C.
Antoine C.

Reputation: 3962

ASP.NET Razor Pages - Conditional redirection

In one of my EF entities, I have a boolean field that indicates whether there is or not a maintainance going.

Thus, I would like to reroute all my pages to a 503 error page only if this boolean is set to true.

I could put the following piece of code in every Page:

if (_context.SystemParameters.First().Maintenance)
    return Redirect("/Error/503");

But this wouldn't be straightforward at all. Is there a best way to achieve such a conditional redirection on all my pages?

Upvotes: 5

Views: 2709

Answers (2)

Kirk Larkin
Kirk Larkin

Reputation: 93293

This can be achieved with a simple custom Middleware component, which would allow for performing the required logic before even entering the MVC pipeline. Here's an example implementation:

app.Use(async (ctx, next) =>
{
    var context = ctx.RequestServices.GetRequiredService<YourContext>();

    if (ctx.Request.Path != "/Error/503" && context.SystemParameters.First().Maintenance)
    {
        ctx.Response.Redirect("/Error/503");
        return;
    }

    await next();
});

Here, ctx is an instance of HttpContext, which is used first to retrieve an instance of YourContext from the DI container and second to perform a redirect. If Maintenance is false, next is invoked in order to pass execution on to the next middleware component.

This call to Use would go before UseMvc in the Startup.Configure method in order to allow for short-circuiting the middleware pipeline. Note that this approach would apply to controllers/views as well as to Razor Pages - it could also be placed further up in the Configure method if there is other middleware that you would want to avoid in the case of being in maintenance mode.

Upvotes: 9

orellabac
orellabac

Reputation: 2665

I would recommend using a PageFilter. If you want this on all your pages maybe implement an IPageFilter or IAsyncPageFilter and register it globally. I think that you can check https://www.learnrazorpages.com/razor-pages/filters if you need more details

Upvotes: 2

Related Questions