Finbuckle.MultiTenant icon indicating copy to clipboard operation
Finbuckle.MultiTenant copied to clipboard

Exceptions logged using OnTenantNotResolved

Open JRuffs7 opened this issue 2 years ago • 3 comments

In our project we would like to handle non-existing tenants by showing them a 404 page. Currently, we do this by: OnTenantNotResolved = async context => { if(context.Context is HttpContext httpContext) { httpContext.Response.StatusCode = 404; await httpContext.Response.CompleteAsync(); } }

However, it seems by changing the Response object then calling CompleteAsync(), it is trying to use HttpResponse.OnStarting() again and is throwing us the error: System.InvalidOperationException: OnStarting cannot be set because the response has already started.

The user receives the 404 correctly and our project does not bomb out, but we would like to resolve the errors that are showing behind the scenes within the logs. Any suggestions?

JRuffs7 avatar May 31 '22 13:05 JRuffs7

I'm also encountering this issue. Any guidance is greatly appreciated

acasciani avatar Jun 15 '22 11:06 acasciani

We were able to get around this by adding a new middleware OnStarting within the OnTenantNotResolved event.

Something like the following

OnTenantNotResolved = context =>
                        {
                            // If no tenant was resolved from the route, then return a 404.
                            if (context.Context is HttpContext httpContext)
                            {
                                // Inject new middleware for this very specific requirement.
                                httpContext.Response.OnStarting(async state =>
                                {
                                    // We need to reference the state for the httpContext, because the state is passed in from the callback.
                                    if (state is HttpContext httpContext)
                                    {
                                        httpContext.Response.Clear();
                                        httpContext.Response.StatusCode = 404;

                                        // We need to flush the cleared response with the new 404.
                                        await httpContext.Response.Body.FlushAsync();
                                    }
                                }, httpContext);
                            }

                            return Task.CompletedTask;
                        }

acasciani avatar Jun 15 '22 17:06 acasciani

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Sep 21 '22 01:09 stale[bot]