簡體   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