在本章中,无涯教程将讨论异常和错误处理,当您的ASP.NET Core应用程序中发生错误时,您可以通过多种方式来处理它们,看看可通过诊断程序包获得的另一中间件,这段中间件将帮助处理错误。
为了模拟错误,转到 app.Run ,如果碰到此中间件时都抛出异常。
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; namespace FirstAppDemo { public class Startup { public Startup() { var builder=new ConfigurationBuilder() .AddJsonFile("AppSettings.json"); Configuration=builder.Build(); } public IConfiguration Configuration { get; set; } //This method gets called by the runtime. //Use this method to add services to the container. //For more information on how to configure your application, //visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } //This method gets called by the runtime. //Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseRuntimeInfoPage(); app.Run(async (context) => { throw new System.Exception("Throw Exception"); var msg=Configuration["message"]; await context.Response.WriteAsync(msg); }); } //Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }
它将抛出异常,并带有非常通用的消息,保存 Startup.cs 页并运行您的应用程序。
您将看到无法加载该资源,出现HTTP 500错误,内部服务器错误,但这不是很有帮助,如果能获取一些异常信息可能会更好。
添加另一个中间件,即 UseDeveloperExceptionPage 。
//This method gets called by the runtime. //Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseDeveloperExceptionPage(); app.UseRuntimeInfoPage(); app.Run(async (context) => { throw new System.Exception("Throw Exception"); var msg=Configuration["message"]; await context.Response.WriteAsync(msg); }); }
此中间件与其他中间件略有不同,其他中间件通常会查看传入的请求并对该请求做出一些决定。
UseDeveloperExceptionPage并不关心传入的请求,因为它会在稍后的管道中进行处理。
它将只调用下一部分中间件,但是随后将查看管道中是否有异常,如果有异常,则该中间件将返回一个错误页面,其中包含有关该异常的一些其他信息。
现在让再次运行该应用程序。它将产生输出,如以下屏幕截图所示。
现在,如果开发中有错误,您将看到一些期望的信息。您还将获得堆栈跟踪,并且可以看到Startup.cs的第37行抛出了未处理的异常。
您还可以看到原始异常的详细信息,所有这些信息对于开发人员都非常有用。实际上,无涯教程可能只想在开发人员运行应用程序时显示此信息。
链接:https://www.learnfk.comhttps://www.learnfk.com/asp.net_core/asp.net-core-exceptions.html
来源:LearnFk无涯教程网
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)