(精华)2020年9月18日 ASP.NET Core 异常页面详解

内置异常页面

public static class Sample02
    {
        public static void Run()
        {
            Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .ConfigureServices(services => services.AddRouting())
                    .Configure(app => app
                        .UseDeveloperExceptionPage()
                        .UseRouting()
                        .UseEndpoints(routeBuilder => routeBuilder.MapGet("/", HandleAsync))
                    ))
                .Build()
                .Run();
        }

        private static Task HandleAsync(HttpContext context)
        {
            return Task.FromException(new InvalidOperationException("This is Exception"));
        }
    }

自定义异常页面

public static class Sample03
{
    public static void Run()
    {
        var options = new ExceptionHandlerOptions
        {
            ExceptionHandler = context => context.Response.WriteAsync("Hello Exception!")
        };

        Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(builder => builder
                .Configure(app => app
                    .UseExceptionHandler(options)
                    .Run(context => Task.FromException(new InvalidOperationException("Throw Exception")))
                ))
            .Build()
            .Run();
    }

}
public static class Sample04
    {
        public static void Run()
        {
            Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .Configure(app => app
                        .UseExceptionHandler(applicationBuilder => applicationBuilder
                            .Run(context => context.Response.WriteAsync("Hello Exception!"))
                        )
                        .Run(context => Task.FromException(new InvalidOperationException("这是一个异常")))
                    ))
                .Build()
                .Run();
        }

    }
public static class Sample05
    {
        public static void Run()
        {
            Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .ConfigureServices(services => services.AddRouting())
                    .Configure(app => app
                        .UseExceptionHandler("/error")
                        .UseRouting()
                        .UseEndpoints(routeBuilder => routeBuilder.MapGet("error", HandleAsync))
                        .Run(context => Task.FromException(new InvalidOperationException("Throw Exception")))
                    ))
                .Build()
                .Run();
        }

        private static Task HandleAsync(HttpContext context)
        {
            return context.Response.WriteAsync("Hello Exception");
        }
    }

状态码错误页面

public static class Sample06
    {
        public static void Run()
        {
            Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .Configure(app => app
                        .UseStatusCodePages("text/plain", "Error ({0})")
                        .Run(context => Task.Run(() => context.Response.StatusCode = 500))
                    ))
                .Build()
                .Run();
        }
    }
public static class Sample07
    {
        private static readonly Random Random = new Random();
        public static void Run()
        {
            Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .Configure(app => app
                        .UseStatusCodePages(Handler)
                        .Run(context => Task.Run(() => context.Response.StatusCode = Random.Next(400,599)))
                    ))
                .Build()
                .Run();
        }

        private static async Task Handler(StatusCodeContext context)
        {
            var response = context.HttpContext.Response;

            if (response.StatusCode < 500)
            {
                await response.WriteAsync($"Client Error ({response.StatusCode})");
            }
            else
            {
                await response.WriteAsync($"Server Error ({response.StatusCode})");
            }
        }
    }
public static class Sample08
    {
        private static readonly Random Random = new Random();
        public static void Run()
        {
            Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .ConfigureServices(collection => collection.AddRouting())
                    .Configure(app => app
                        .UseStatusCodePagesWithRedirects("/error/{0}")
                        .UseRouting()
                        .UseEndpoints(routeBuilder => routeBuilder.MapGet("error/{status_code}", HandlerError))
                        .Run(context => Task.Run(() => context.Response.StatusCode = Random.Next(400,599)))
                    ))
                .Build()
                .Run();
        }

        private static async Task HandlerError(HttpContext context)
        {
            var code = context.GetRouteData().Values["status_code"];
            await context.Response.WriteAsync($"Error ({code})");
        }
    }
public static class Sample09
    {
        private static readonly Random Random = new Random();
        public static void Run()
        {
            Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .ConfigureServices(collection => collection.AddRouting())
                    .Configure(app => app
                        .UseStatusCodePagesWithReExecute("/error/{0}")
                        .UseRouting()
                        .UseEndpoints(routeBuilder => routeBuilder.MapGet("error/{status_code}", HandlerError))
                        .Run(context => Task.Run(() => context.Response.StatusCode = Random.Next(400,599)))
                    ))
                .Build()
                .Run();
        }

        private static async Task HandlerError(HttpContext context)
        {
            var code = context.GetRouteData().Values["status_code"];
            await context.Response.WriteAsync($"Error ({code})");
        }
    }

实际中使用异常设置

首先安装如下包

Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
class Program
    {
        static void Main(string[] args)
        {
            var options = new DeveloperExceptionPageOptions
            {
                SourceCodeLineCount = 3
            };

            Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .ConfigureServices(collection => collection
                        .AddRouting()
                        .AddControllersWithViews()
                        .AddRazorRuntimeCompilation())
                    .Configure(app=>app
                        .UseDeveloperExceptionPage(options)
                        .UseRouting()
                        .UseEndpoints(routeBuilder => routeBuilder.MapControllers()))
                )
                .Build()
                .Run();
        }
    }

    public class HomeController : Controller
    {
        [HttpGet("/")]
        public IActionResult Index() => View();
    }
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页