.net core实现404错误跳转指定页

如果输入的地址不存在或者原因地址被删除等问题,我们可以用下面方法实现跳转到指定的页面,在这里我是跳转到了首页代码如下
public class Jump404Middleware
{
    private readonly RequestDelegate next;
    public Jump404Middleware(RequestDelegate next)
    {
        this.next = next;
    }
    public async Task Invoke(Microsoft.AspNetCore.Http.HttpContext context)
    {
        await next.Invoke(context);
        var response = context.Response;
        //状态如果是404,跳转到主页
        if (response.StatusCode == 404)
        {
            response.Redirect("/");
        }
    }
}
public static class Jump404MiddlewareExtension
{
    public static void UseJump404(this IApplicationBuilder app)
    {
        app.UseMiddleware<Jump404Middleware>();
    }
}
最后在NET Core中Startup类的Configure方法中使用Jump404Middleware中间件即可:代码如下
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //...
    app.UseJump404();
}

转载请保留原创地址 http://www.luofenming.com/show.aspx?id=ART2019111000001

评论