ASP.NET Core - 异常处理

ASP.NET Core - 异常处理 首页 / ASP.Net Core入门教程 / 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并不关心传入的请求,因为它会在稍后的管道中进行处理。

  • 它将只调用下一部分中间件,但是随后将查看管道中是否有异常,如果有异常,则该中间件将返回一个错误页面,其中包含有关该异常的一些其他信息。

现在让再次运行该应用程序。它将产生输出,如以下屏幕截图所示。

Internal Server Error

现在,如果开发中有错误,您将看到一些期望的信息。您还将获得堆栈跟踪,并且可以看到Startup.cs的第37行抛出了未处理的异常。

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

链接:https://www.learnfk.comhttps://www.learnfk.com/asp.net_core/asp.net-core-exceptions.html

来源:LearnFk无涯教程网

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

代码精进之路 -〔范学雷〕

视觉笔记入门课 -〔高伟〕

重学线性代数 -〔朱维刚〕

张汉东的Rust实战课 -〔张汉东〕

性能优化高手课 -〔尉刚强〕

Redis源码剖析与实战 -〔蒋德钧〕

手把手带你搭建秒杀系统 -〔佘志东〕

大厂设计进阶实战课 -〔小乔〕

Web 3.0入局攻略 -〔郭大治〕

好记忆不如烂笔头。留下您的足迹吧 :)