asp.net 拦截html,关于c#:如何在-ASPNET-Core-中实现全局异常拦截
異樣是一種運行時謬誤,當異樣沒有失去適當的解決,很可能會導致你的程序意外終止,這篇就來討論一下如何在 ASP.Net Core MVC 中實現全局異樣解決,我會用一些 樣例代碼 和 截圖 來闡明這些概念。
全局異樣解決
其實在 ASP.Net Core MVC 框架中曾經有了全局異樣解決的機制,你能夠在一個中心化的中央應用 全局異樣解決中間件 來進行異樣攔擋,如果不必這種中心化形式的話,你就只能在 Controller 或者 Action 作用域上獨自解決,這會導致異樣解決代碼零散在我的項目各處,不好保護也特地麻煩,不是嗎?
第二種解決 全局異樣 的做法就是應用 exception filter,在本篇中,我籌備跟大家聊一聊 全局異樣解決中間件 和 UseExceptionHandler 辦法來管控異樣。
應用 UseExceptionHandler 擴大辦法
UseExceptionHandler 擴大辦法可能將 ExceptionHandler 中間件注冊到 Asp.net Core 的 申請解決管道 中,而后在 IExceptionHandlerFeature 接口的實例中獲取 異樣對象,上面的代碼片段展現了如何應用 UseExceptionHandler 辦法來截獲全局異樣。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
var exception = context.Features.Get();
if (exception != null)
{
var error = new ErrorMessage()
{
Stacktrace = exception.Error.StackTrace,
Message = exception.Error.Message
};
var errObj = JsonConvert.SerializeObject(error);
await context.Response.WriteAsync(errObj).ConfigureAwait(false);
}
});
}
);
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
上面是代碼中援用的 ErrorMessage 類的定義。
public class ErrorMessage
{
public string Message { get; set; }
public string Stacktrace { get; set; }
}
配置 全局異樣中間件
大家都曉得,ASP.Net Core MVC 我的項目中都會有一個 Startup.cs 文件,能夠在 Configure 辦法下配置 全局異樣攔擋中間件 代碼,如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template:
"{controller=Home}/{action=Index}/{id?}");
});
}
能夠著重看一下下面的 app.UseExceptionHandler("/Error");,這里的 UseExceptionHandler 實現了 pipeline 注冊,一旦應用程序呈現了未解決異樣,那么會主動將 用戶 導向 /Error 頁面。
你能夠用 UseStatusCodePagesWithReExecute 擴大辦法給 pipeline 增加一些狀態碼頁面,這是什么意思呢? 其實也就是 http 500 導向 500 頁面, http 404 導向 404 頁面,上面的代碼片段展現了批改后的 Configure 辦法代碼。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseStatusCodePagesWithReExecute("/Error/NotFound/{0}");
}
//Other code
}
應用 ErrorController
在 HomeController 下有一個專門處理錯誤的 action 辦法,這里咱們不應用這個 action,你能夠把它刪掉,接下來我籌備定義一個專門的 ErrorController,外面蘊含了一個路由為 /Error 的 action 辦法。
public class ErrorController : Controller
{
[HttpGet("/Error")]
public IActionResult Index()
{
IExceptionHandlerPathFeature iExceptionHandlerFeature = HttpContext.Features.Get();
if (iExceptionHandlerFeature != null)
{
string path = iExceptionHandlerFeature.Path;
Exception exception = iExceptionHandlerFeature.Error;
//Write code here to log the exception details
return View("Error",iExceptionHandlerFeature);
}
return View();
}
[HttpGet("/Error/NotFound/{statusCode}")]
public IActionResult NotFound(int statusCode)
{
var iStatusCodeReExecuteFeature =HttpContext.Features.Get();
return View("NotFound",iStatusCodeReExecuteFeature.OriginalPath);
}
}
你能夠用 IExceptionHandlerPathFeature 來獲取異樣相干信息,也能夠用 IStatusCodeReExecuteFeature 來獲取 http 404 異樣時過后的申請門路,對了,要想用上 IExceptionHandlerPathFeature 和 IStatusCodeReExecuteFeature,要記得在 nuget 上裝置了 Microsoft.AspNetCore.Diagnostics 包,上面的代碼展現了如何獲取異樣產生時刻的路由地址。
string route = iExceptionHandlerFeature.Path;
如果想獲取異樣的詳細信息,能夠應用如下語句。
var exception = HttpContext.Features.Get();
一旦獲取了這個路由地址和異樣的詳細信息,就能夠將它記錄到你的日志文件中,可供后續仔細分析。
應用 View 展現錯誤信息
能夠創立一個 View 來展現呈現的錯誤信息,上面時 Error ViewPage 的具體代碼。
@model Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
Error: @Model.Error.Message
@Model.Error.StackTrace
@Model.Error.InnerException
上面是 NotFound 頁面的 代碼
@model string
@{
ViewData["Title"] = "NotFound";
Layout = "~/Views/Shared/_Layout.cshtml";
}
Error: The requested URL @Model was not found!
當初能夠把程序跑起來了,你會看到如下的錯誤信息。
如果你嘗試關上一個不存在的頁面, 會主動跳轉到 ErrorController.NotFound 所包裝的 404 形容信息。
ASP.NET Core 中內置了 全局異樣解決,你能夠利用這項技術在一個集中化的中央去截獲你應用程序中的所有異樣信息,當然你也能夠基于環境的不同采取不必的異樣解決措施,比如說:開發環境,測試環境,生產環境 等等。
譯文鏈接:https://www.infoworld.com/art…
更多高質量干貨:參見我的 GitHub: dotnetfly
總結
以上是生活随笔為你收集整理的asp.net 拦截html,关于c#:如何在-ASPNET-Core-中实现全局异常拦截的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小米13 Lite真机照泄露:比iPho
- 下一篇: c# list转为json_ASP.ne