我有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