c# - 在 asp.net 核心中处理异常?

标签 c# asp.net-core asp.net-core-mvc coreclr

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

然而,它仅在 Controller 内部发生异常时才有效。如果异常发生在 Controller 外部,例如在我的自定义中间件中,则用户不会被重定向到错误页面。

如果中间件出现异常,我如何将用户重定向到“错误”页面。

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

最佳答案

你可以使用UseExceptionHandler()来处理异常,把这段代码放在你的 Startup.cs.

UseExceptionHandler can be used to handle exceptions globally. You can get all the details of exception object like Stack Trace, Inner exception and others. And then you can show them on screen. Here

在这里您可以阅读更多关于这个诊断中间件的信息,并了解如何使用 IExceptionFilter 以及如何创建您自己的自定义异常处理程序。

   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(),如果您使用它,它总是显示默认错误页面。

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

关于c# - 在 asp.net 核心中处理异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40614184/

相关文章:

c# - 为什么 AddMvc 需要 Action<MvcOptions> 而不是 MvcOptions?

asp.net-core - 使用 AD B2C 时如何添加 OnTokenValidated 事件处理程序?

asp.net-core - dotnet 包在 .net 核心 mvc 应用程序中不起作用

c# - 异步socket,接收字符串消息

c# - Autofac 随机无参数公共(public)构造函数。错误

C# 错误 - 由于可选参数或其他原因?

asp.net-core - OpenIddict:当两个或多个服务实例计数时出现 401 错误

c# - ASP.Net Core 在运行时注册 Controller

c# - ASP.NET 5 中 System.Web.Mvc.Html.InputExtensions 的等价物是什么?

c# - unity : Remove The selected object from random.范围