How do I redirect to a View instead of UseDeveloperExceptionPage on Specific Http Error Status

Viewed 109

I have a .NET Core MVC environnement. I want to manage a login routine when server give 403 error.

I currently use this configuration in my Startup.cs file :

if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error/500");
            app.UseHsts();
        }

But I would like something like :

if (env.IsDevelopment())
        {
            if ( error === 403 )
                app.UseExceptionHandler("/Home/MyCustomError");
            else
                app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error/500");
            app.UseHsts();
        }

How can I deal with it ?

I tried to make what Microsoft explained with app.UseExceptionHandler in both case. In this way, I want to do what I want and show error if error is not 403 and return login View if it is. The problem with this solution is that the displayed error is not a nice detailed page for debugging like app.UseDeveloperExceptionPage render.

2 Answers

You can try to use UseStatusCodePagesWithReExecute.Here is a demo(I test with 404,you can also add other status code error page to Error folder in the demo):

Startup:

if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseStatusCodePagesWithReExecute("/StatusCode", "?code={0}");

StatusCodeController:

public class StatusCodeController : Controller
    {
        public IActionResult Index(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                code = "Unknown.cshtml";
            }
            return View($"/Views/Shared/Error/{code}.cshtml");
        }
    }

Error folder:

enter image description here

404.cshtml:

<h1>404</h1>

result: enter image description here

You can also try UseStatusCodePagesWithRedirects.

Try this

if (env.IsDevelopment())
{
    app.Use(async (context, next) =>
    {
        await next();

        if (context.Response.StatusCode == 403 && !context.Response.HasStarted)
        {
            context.Response.Redirect("/Home/MyCustomError");
        }
    });
    
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error/500");
    app.UseHsts();
}
Related