I updated the code in my installation in src/Presentation/Nop.Web.Framework/Infrastructure/Extensions/ApplicationBuilderExtensions.cs
original line 173 with redirect:
context.HttpContext.Response.Redirect(context.HttpContext.Request.PathBase + pageNotFoundPath);
replaced by my custom function
await CreateHandlerAsync(context, pageNotFoundPath);
and the method is
private static async Task CreateHandlerAsync(StatusCodeContext context, string path)
{
var newPath = new PathString(
string.Format(CultureInfo.InvariantCulture, path, context.HttpContext.Response.StatusCode));
var originalPath = context.HttpContext.Request.Path;
var originalQueryString = context.HttpContext.Request.QueryString;
var routeValuesFeature = context.HttpContext.Features.Get<IRouteValuesFeature>();
// Store the original paths so the app can check it.
context.HttpContext.Features.Set<IStatusCodeReExecuteFeature>(new StatusCodeReExecuteFeature()
{
OriginalPathBase = context.HttpContext.Request.PathBase.Value!,
OriginalPath = originalPath.Value!,
OriginalQueryString = originalQueryString.HasValue ? originalQueryString.Value : null,
Endpoint = context.HttpContext.GetEndpoint(),
RouteValues = routeValuesFeature?.RouteValues
});
// An endpoint may have already been set. Since we're going to re-invoke the middleware pipeline we need to reset
// the endpoint and route values to ensure things are re-calculated.
context.HttpContext.SetEndpoint(endpoint: null);
if (routeValuesFeature != null)
{
routeValuesFeature.RouteValues = null!;
}
context.HttpContext.Request.Path = newPath;
context.HttpContext.Request.QueryString = QueryString.Empty;
try
{
await context.Next(context.HttpContext);
}
finally
{
context.HttpContext.Request.QueryString = originalQueryString;
context.HttpContext.Request.Path = originalPath;
context.HttpContext.Features.Set<IStatusCodeReExecuteFeature?>(null);
}
}
This method was inspired by private method Microsoft.AspNetCore.Builder.StatusCodePagesExtensions.CreateHandler used in UseStatusCodePagesWithReExecute.
Now the website directly returns a 404 page without any redirection, which was highly appreciated by our SEO consultants.
Does that seem okay to you? I could make a PR on it if so.