When throwing a HttpError.Forbidden, what's the best way to render a specific view?

On a service endpoint I want to throw new HttpError(HttpStatusCode.Forbidden), and that would render a view on /forbidden.cshml

I think previously customErrorHttpHandlers[HttpStatusCode.Forbidden] = new RazorHandler("/forbidden.cshml"); used to work, but now on 6.1.1 that does not seem to work.

What is the correct way to accomplish this?

Hi @brunomlopes, can you provide more info? Eg, what error you are getting, how you have your AppHost configured with Razor? A minimal reproduction of the issue would be best to help find root cause of the issue. Thanks.

With the razor template created with x new razor, I had expected that an http erro thrown on the service like

                throw new HttpError(HttpStatusCode.Forbidden);

With the following configuration

            appHost.CustomErrorHttpHandlers[HttpStatusCode.NotFound] = new RazorHandler("/notfound");
            appHost.CustomErrorHttpHandlers[HttpStatusCode.Forbidden] = new RazorHandler("/forbidden");

Would render the /forbidden page.
The corrent solution we’ve found includes setting a service exception handler:

          appHost.ServiceExceptionHandlers.Add((req, request, exception) =>
            {
                if(exception is HttpError {StatusCode: HttpStatusCode.Forbidden})
                    req.SetView("Forbidden");
                return null;
            });

Which is not 100% the same, since that is a “Forbidden” view , and not the “/forbidden” page.

Also, we wanted to show the forbidden page on all StatusCode 403, which this solution doesn’t do.

Are we missing something?

1 Like

It’s because the CustomErrorHttpHandlers are populated when AuthFeature is registered, overriding any existing configuration.

It will work if they’re populated after plugins are loaded:

public class ConfigureUi : IHostingStartup
{
    public void Configure(IWebHostBuilder builder) => builder
        .ConfigureAppHost(afterPluginsLoaded: appHost =>
        {
            appHost.CustomErrorHttpHandlers[HttpStatusCode.NotFound] = new RazorHandler("/notfound");
            appHost.CustomErrorHttpHandlers[HttpStatusCode.Forbidden] = new RazorHandler("/forbidden");
        });
}

I’ve added a fix to only set CustomErrorHandlers if they’re not already populated in this commit so the existing configuration will work in the next release.