Show 404 status and page-not-found View without actually redirecting to pagenotfound Nopcommerce 4.5

68 Views Asked by At

Using Nopcommerce V.4.5

Whenever there is a 404 error it redirect to /pagenotfound.

I am trying for it to show the same View on the original URL that was 404.

So far:

I have added a custom middleware on NopRoutingStartup.cs

public void Configure(IApplicationBuilder application)
{
  application.UseMiddleware<Custom404Middleware>();
  application.UseMiniProfiler();
  application.UseRouting();
}

Custom404Middleware.cs

    internal class Custom404Middleware
    {
    private readonly RequestDelegate _next;

    public Custom404Middleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var originalPath = context.Request.Path.Value;
        var originalQueryString = context.Request.QueryString.Value;
        await _next(context);

        if (context.Response.StatusCode == StatusCodes.Status404NotFound && !context.Response.HasStarted)
        {
           
            context.Response.ContentType = "text/plain";
            await context.Response.WriteAsync("Custom 404 Page Not Found");

           }
       }
   }

It works and I see : Custom 404 Page Not Found on 404. How can I here show the View I want?

Any suggestions ?

1

There are 1 best solutions below

1
On

I don't suggest returning views in middleware how ever if you wanna do that, here's your updated invoke function:

public async Task Invoke(HttpContext context)
{
    var originalPath = context.Request.Path.Value;
    var originalQueryString = context.Request.QueryString.Value;
    await _next(context);

    if (context.Response.StatusCode == StatusCodes.Status404NotFound && !context.Response.HasStarted)
    {
       
        context.Response.ContentType = "text/plain";
        await context.Response.WriteAsync("Custom 404 Page Not Found");
        var actionContext = new ActionContext(context, context.GetRouteData(), new ActionDescriptor());

        var executor = serviceProvider.GetRequiredService<IActionResultExecutor<ViewResult>>();

        var viewResult = new ViewResult
        {
            ViewName = "PageNotFound",
            StatusCode = StatusCodes.Status404NotFound,
            ViewData = new ViewDataDictionary(
                           new EmptyModelMetadataProvider(), new ModelStateDictionary())
        };

        await executor.ExecuteAsync(actionContext, viewResult);
    }
}