Search code examples
c#asp.netasp.net-coreasp.net-core-2.1asp.net-core-2.2

How can I redirect a user when a specific exception is cought with ASP.NET Core 2.2 project?


I have a project that is written using C# on the top of ASP.NET Core 2.2 framework.

The application throws a custom exception when something unexpected happens.

For example, if the app can't find a default setting in the database, it throws ApplicationIsNotSetupException(). This exception indicates that the admin did not install the project using the installation process as they should. Therefore, I want to direct them to the installation controller. (i.e, SetupController.Install())

How can I redirect the user to s specific route if the ApplicationIsNotSetupException() was caught?


Solution

  • Here's a possibility:

    // This should be before app.UseMvc
    app.Use(async (context, next) =>
    {
        try
        {
            await next();
        }
        catch (ApplicationIsNotSetupException)
        {
            context.Response.Redirect("/setup/install");
        }
    });
    

    I found this Question, there are some good answers there too.