Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 858
Antoine C. Avatar asked Dec 09 '18 14:12

Antoine C.


2 Answers

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.

like image 107
Kirk Larkin Avatar answered Oct 06 '22 20:10

Kirk Larkin


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

like image 1
orellabac Avatar answered Oct 06 '22 21:10

orellabac