繁体   English   中英

如何从netcore中的startup.cs中删除app.UseExceptionHandler到另一个文件?

[英]How to remove app.UseExceptionHandler from the startup.cs in netcore to a other file?

我有一个 netcore 应用程序。 我想从 startup.cs 中删除 app.UseExceptionHandler 方法到一个单独的类。 这样 startup.cs 类会更小。

所以整个方法看起来像这样:


 // Only in development envirionment the hole stacktrace is returned.
            app.UseExceptionHandler(
                    options =>
                    {
                        options.Run(
                            async context =>
                            {
                                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                                context.Response.ContentType = "application/json";
                                var ex = context.Features.Get<IExceptionHandlerFeature>();
                                if (ex != null)
                                {
                                    ILogger logger = loggerFactory.CreateLogger("unhandled exception");
                                    logger.LogCritical(1, ex.Error, "unhandled exception");
                                    Dictionary<string, string> errorObject;

                                    if (appSettings.IsDebug) //TODO: change this to env.IsDevelopment() when envirionment is set on servers?
                                    {
                                        errorObject = new Dictionary<string, string>
                                        {
                                            {"message" , ex.Error.Message },
                                            {"stackTrace", ex.Error.StackTrace },
                                            {"source", ex.Error.Source}
                                        };
                                    }
                                    else
                                    {
                                        // Do not show any information in production envirionment.
                                        errorObject = new Dictionary<string, string>
                                        {
                                            { "message" , "An error occurred!" }
                                        };
                                    }

                                    await context.Response.WriteAsync(JsonConvert.SerializeObject(errorObject)).ConfigureAwait(false);
                                }
                            });
                    }
            );

所以我做了一个类:

public class ErrorHandlingMiddleware
    {


        public static IServiceCollection HanldeErrors()
        {

            app.UseExceptionHandler(
                       options =>
                        {
                            options.Run(
                                async context =>
                                {
                                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                                    context.Response.ContentType = "application/json";
                                    var ex = context.Features.Get<IExceptionHandlerFeature>();
                                    if (ex != null)
                                    {
                                        ILogger logger = loggerFactory.CreateLogger("unhandled exception");
                                        logger.LogCritical(1, ex.Error, "unhandled exception");
                                        Dictionary<string, string> errorObject;

                                        if (appSettings.IsDebug) //TODO: change this to env.IsDevelopment() when envirionment is set on servers?
                                    {
                                            errorObject = new Dictionary<string, string>
                                            {
                                            {"message" , ex.Error.Message
    },
                                            {"stackTrace", ex.Error.StackTrace
},
                                            {"source", ex.Error.Source}
                                            };
                                        }
                                        else
                                        {
                                        // Do not show any information in production envirionment.
                                        errorObject = new Dictionary<string, string>
                                            {
                                            { "message" , "An error occurred!" }
                                            };
                                        }

                                        await context.Response.WriteAsync(JsonConvert.SerializeObject(errorObject)).ConfigureAwait(false);
                                    }
                                });
                        }
                );



        }
    }

但是我不知道我必须对这个类做出什么改变? 我必须如何自定义它?

好吧,我现在是这样的:

 public static class ErrorHandlingMiddleware
    {

        public static void  HanldeErrors(IApplicationBuilder app, ILoggerFactory loggerFactory, IOptions<AppSettings> appSettingsOptions)
        {

            var appSettings = appSettingsOptions.Value;

            app.UseExceptionHandler(
                       options =>
                        {
                            options.Run(
                                async context =>
                                {
                                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                                    context.Response.ContentType = "application/json";
                                    var ex = context.Features.Get<IExceptionHandlerFeature>();
                                    if (ex != null)
                                    {
                                        ILogger logger = loggerFactory.CreateLogger("unhandled exception");
                                        logger.LogCritical(1, ex.Error, "unhandled exception");
                                        Dictionary<string, string> errorObject;

                                        if (appSettings.IsDebug) //TODO: change this to env.IsDevelopment() when envirionment is set on servers?
                                    {
                                            errorObject = new Dictionary<string, string>
                                            {
                                            {"message" , ex.Error.Message
    },
                                            {"stackTrace", ex.Error.StackTrace
},
                                            {"source", ex.Error.Source}
                                            };
                                        }
                                        else
                                        {
                                        // Do not show any information in production envirionment.
                                        errorObject = new Dictionary<string, string>
                                            {
                                            { "message" , "An error occurred!" }
                                            };
                                        }

                                        await context.Response.WriteAsync(JsonConvert.SerializeObject(errorObject)).ConfigureAwait(false);
                                    }
                                });
                        }
                );
        }
    }

而我的 startup.cs 看起来像这样?


   public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<AppSettings> appSettingsOptions)
{


            app.UseMiddleware(typeof(ErrorHandlingMiddleware));

            app.UseStaticFiles();

}

但这是正确的方法吗?

谢谢

发布的代码没有创建中间件类,它只是将方法提取到一个单独的静态类中。 没有必要将该类注册为中间件——事实上这是不可能的,因为它没有实现 IMiddleWare

此静态方法可以被转化成一个扩展方法太,加入this第一参数:

public static void  HanldeErrors(this IApplicationBuilder app, ILoggerFactory loggerFactory, IOptions<AppSettings> appSettingsOptions)

应该调用该方法而不是UseExceptionHandler ,例如:

 HanldeErrors(app,loggerFactory, appSettingsOptions);

或者

 app.HanldeErrors(loggerFactory, appSettingsOptions);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM