久久96国产精品久久久-久久发布国产伦子伦精品-久久精品国产精品青草-久久天天躁夜夜躁狠狠85麻豆

技術員聯(lián)盟提供win764位系統(tǒng)下載,win10,win7,xp,裝機純凈版,64位旗艦版,綠色軟件,免費軟件下載基地!

當前位置:主頁 > 教程 > 服務器類 >

ASP.NET Core異常和錯誤處理教程

來源:技術員聯(lián)盟┆發(fā)布時間:2017-07-19 06:19┆點擊:

在這一章,我們將討論異常和錯誤處理。當 ASP.NET Core應用程序中發(fā)生錯誤時,您可以以各種不同的方式來處理。讓我們來看看通過添加一個中間件來處理異常情況,這個中間件將幫助我們處理錯誤。

要模擬出錯,讓我們轉到應用程序,運行,如果我們只是拋出異常的話,看看程序是如何運轉轉的。

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 ?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頁面并運行您的應用程序。

ASP.NET Core異常和錯誤處理 三聯(lián)

您將看到我們未能加載此資源。出現(xiàn)了一個 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); }); }

這個中間件與其他的有點不同,其他中間件通常監(jiān)聽傳入的請求并對請求做一些響應。

UseDeveloperExceptionPage不會如此在意傳入的請求在之后的管道會發(fā)生什么。

它只是調用下一個中間件,然后再等待,看看管道中是否會出現(xiàn)異常,如果有異常,這塊中間件會給你一個關于該異常的錯誤頁面。

現(xiàn)在讓我們再次運行應用程序。將會產(chǎn)生一個如下面的屏幕截圖所示的輸出。

ASP.NET Core異常和錯誤處理教程

現(xiàn)在如果程序中出現(xiàn)異常,您將在頁面中看到一些想要看到的異常信息。你也會得到一個堆棧跟蹤:這里可以看到Startup.cs第37行有一個未處理的異常拋出。

所有這些異常信息對開發(fā)人員將非常有用。事實上,我們可能只希望當開發(fā)人員運行應用程序時才顯示這些異常信息。