我有asp.net核心應用程序。當發生異常時(在非開發環境中),配置方法的實現將用戶重定向到「錯誤」頁面在asp.net核心處理異常?
但是,只有當控制器內部出現異常時,它纔有效。如果異常發生在控制器之外,例如在我的自定義中間件中,則用戶不會重定向到錯誤頁面。
如果中間件出現異常,我該如何將用戶重定向到「錯誤」頁面。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseSession();
app.UseMyMiddleware();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
更新1
我上面用下面的兩行中缺少在初始後更新的代碼。
app.UseSession();
app.UseMyMiddleware();
此外,我發現爲什麼app.UseExceptionHandler
無法重定向到錯誤頁面。
當我的中間件代碼出現異常時,app.UseExceptionHandler("\Home\Error")
按預期重定向到\Home\Error
;但由於這是一個新的請求,我的中間件再次執行並再次拋出異常。
所以要解決這個問題我改變了我的中間件僅if context.Request.Path != "/Home/Error"
我不知道要執行,如果這是解決這個問題,但其工作的正確方法。
public class MyMiddleWare
{
private readonly RequestDelegate _next;
private readonly IDomainService _domainService;
public MyMiddleWare(RequestDelegate next, IDomainService domain)
{
_next = next;
_domainService = domain;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Path != "/Home/Error")
{
if (context.User.Identity.IsAuthenticated && !context.Session.HasKey(SessionKeys.USERINFO))
{
// this method may throw exception if domain service is down
var userInfo = await _domainService.GetUserInformation(context.User.Name).ConfigureAwait(false);
context.Session.SetUserInfo(userInfo);
}
}
await _next(context);
}
}
public static class MyMiddleWareExtensions
{
public static IApplicationBuilder UseMyMiddleWare(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyMiddleWare>();
}
}
該示例中的哪個位置是您的自定義中間件?我認爲**'UseExeptionHandler'應該能夠處理它,但是您的中間件需要在**之後註冊**。 – Tseng