ASP.NET Core - 例外

在本章中,我们将讨论异常和错误处理.当您的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 页面并运行您的应用程序.

Generic Message

您将看到我们无法加载此资源.有一个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行抛出了未处理的异常.

您还可以看到原始异常详细信息,所有这些信息都可以对开发人员非常有用.实际上,我们可能只想在开发人员运行应用程序时显示此信息.