显示 404 状态和 page-not-found 视图,而不实际重定向到 pagenotfound Nopcommerce 4.5

问题描述 投票:0回答:1

使用Nopcommerce V.4.5

每当出现 404 错误时,它都会重定向到 /pagenotfound。

我正在尝试让它在原始 URL 上显示 404 相同的视图。

到目前为止:

我在

NopRoutingStartup.cs

上添加了自定义中间件
public void Configure(IApplicationBuilder application)
{
  application.UseMiddleware<Custom404Middleware>();
  application.UseMiniProfiler();
  application.UseRouting();
}

自定义404中间件.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");

           }
       }
   }

它有效,我在 404 上看到:

Custom 404 Page Not Found
。我怎样才能在这里显示我想要的视图?

有什么建议吗?

c# .net-core nopcommerce asp.net-core-middleware nopcommerce-4.5
1个回答
0
投票

我不建议在中间件中返回视图,如果您想这样做,这是更新的调用函数:

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.