# 相关资源

  • Blazor 导航 - 在找不到内容时提供自定义内容
  • ASP.Net 处理错误 - UseStatusCodePagesWithRedirects

# 简易方法

在构建服务时使用 UseStatusCodePagesWithRedirects 方法,来指定某个错误码应当重定向至哪个地址。缺点也很明显,错误码必须写在地址里,并不美观。

# 服务构建

1
app.UseStatusCodePagesWithRedirects("/404");

# 页面

1
2
@page "/404"
<h1>Not Found</h1>

# 中间件方法

我们可以做一个中间件来处理 404 结果,当 StatusCode404 时,就重定向至自定义的路径

# 中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class NotFoundRedirectMiddleware
{
private readonly RequestDelegate _next;

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

public async Task Invoke(HttpContext httpContext)
{
await _next(httpContext);
if (httpContext.Response.StatusCode == StatusCodes.Status404NotFound && !httpContext.Response.HasStarted)
{
// 防止死循环,避免对 /NotFound 自身进行重定向
if (!httpContext.Request.Path.StartsWithSegments("/NotFound", StringComparison.OrdinalIgnoreCase))
{
httpContext.Response.Clear();
httpContext.Response.Redirect("/NotFound");
}
}
}
}

public static class NotFoundRedirectMiddlewareExtensions
{
public static IApplicationBuilder UseNotFoundRedirectMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<NotFoundRedirectMiddleware>();
}
}

# 服务构建

1
app.UseNotFoundRedirectMiddleware();

# 404 页面

1
2
@page "/NotFound"
<h1>Not Found</h1>