简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM