Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 544
Alexy Avatar asked Dec 17 '25 14:12

Alexy


1 Answers

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();
}
like image 122
FireAlkazar Avatar answered Dec 19 '25 03:12

FireAlkazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!