I have a main asp.net application. Implementation of the configure method redirects the user to the Error page when an exception occurs (in an environment without development)
However, it only works if an exception occurs inside the controller. If an exception occurs outside the controller, for example, in my custom middleware, the user is not redirected to the error page.
How to redirect the user to the Error page if there is an exception in the middleware.
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?}"); }); }
Update 1
I updated the code above with the following two lines missing from the original post.
app.UseSession(); app.UseMyMiddleware();
I also found why app.UseExceptionHandler could not redirect to the error page.
When there is an exception in my intermediate code, app.UseExceptionHandler("\Home\Error") redirected to \Home\Error , as expected; but since this is a new request, my middleware ran again and threw an exception again.
So to solve the problem, I changed my middleware to only execute if context.Request.Path != "/Home/Error"
I am not sure if this is the right way to solve this problem, but its work.
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)) {
c # asp.net-core asp.net-core-mvc coreclr
LP13
source share