在ASP.NET Core中处理异常? [英] Handling exception in asp.net core?

查看:184
本文介绍了在ASP.NET Core中处理异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有asp.net核心应用程序.发生异常时(在非开发环境中),配置方法的实现将用户重定向到错误"页面

I have asp.net core application. The implementation of configure method redirects the user to "Error" page when there is an exception ( in non Development environment)

但是,仅当异常发生在控制器内部时,它才有效.如果异常发生在控制器外部(例如在我的自定义中间件中),则不会将用户重定向到错误页面.

However it only works if the exception occurs inside controller. If exception occurs outside of controller, for example in my custom middleware, then the user does not get redirected to error page.

如果中间件出现异常,如何将用户重定向到错误"页面.

How do i redirect user to "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?}");
        });
    }

更新1
我更新了上面的代码,其中包含最初发布时缺少的以下两行.

Update 1
I updated code above with the following two lines that were missing in initial post.

        app.UseSession();
        app.UseMyMiddleware();

我也找到了为什么app.UseExceptionHandler无法重定向到错误页面的原因. 当我的中间件代码中出现异常时,app.UseExceptionHandler("\Home\Error")会按预期重定向到\Home\Error.但是由于这是一个新请求,因此我的中间件再次执行并再次引发异常.
因此,为了解决此问题,我将中间件更改为仅执行if context.Request.Path != "/Home/Error"

Also I found why app.UseExceptionHandler was not able to redirect to Error page.
When there is an exception in my middleware code, app.UseExceptionHandler("\Home\Error") is redirecting to \Home\Error as expected; but since that is a new request, my middleware was executing again and throwing exception again.
So to solve the issue i changed my middleware to execute only if context.Request.Path != "/Home/Error"

我不确定这是否是解决此问题的正确方法,但可以解决此问题.

I am not sure if this is the correct way to solve this issue but its working.

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>();
    }
 }

推荐答案

您可以用来处理异常UseExceptionHandler(),将此代码放入您的 Startup.cs.

You can use to handle exceptions UseExceptionHandler(), put this code in your Startup.cs.

UseExceptionHandler可用于全局处理异常.您可以获取异常对象的所有详细信息,例如堆栈跟踪,内部异常等.然后,您可以在屏幕上显示它们. 此处

在这里,您可以阅读有关此诊断中间件的更多信息,并找到如何使用IExceptionFilter并通过创建自己的自定义异常处理程序.

Here You can read more about this diagnostic middleware and find how using IExceptionFilter and by creating your own custom exception handler.

   app.UseExceptionHandler(
                options =>
                {
                    options.Run(
                        async context =>
                        {
                            context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
                            context.Response.ContentType = "text/html";
                            var ex = context.Features.Get<IExceptionHandlerFeature>();
                            if (ex != null)
                            {
                                var err = $"<h1>Error: {ex.Error.Message}</h1>{ex.Error.StackTrace}";
                                await context.Response.WriteAsync(err).ConfigureAwait(false);
                            }
                        });
                }
            );

您还必须删除默认设置,例如UseDeveloperExceptionPage(),如果使用它,它将始终显示默认错误页面.

You have to also delete default setting like UseDeveloperExceptionPage(), if you use it, it always show default error page.

   if (env.IsDevelopment())
        {
            //This line should be deleted
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

这篇关于在ASP.NET Core中处理异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆