使用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
。我怎样才能在这里显示我想要的视图?
有什么建议吗?
我不建议在中间件中返回视图,如果您想这样做,这是更新的调用函数:
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);
}
}